netty------Helloworld

今天分享一下netty的helloworld,簡單容易上手。
首先看server(注釋已在代碼中標(biāo)明)

package com.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {
    
    public static void main(String[] args) throws InterruptedException {
        //用來接收客戶端傳進來的連接
        NioEventLoopGroup boss = new NioEventLoopGroup();
        //用來處理已被接收的連接
        NioEventLoopGroup work = new NioEventLoopGroup();
        //輔助類 用于幫助我們創(chuàng)建netty服務(wù)
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, work)
        .channel(NioServerSocketChannel.class)//設(shè)置NIO模式
        .option(ChannelOption.SO_BACKLOG, 1024)//設(shè)置tcp緩沖區(qū)
        .childOption(ChannelOption.SO_SNDBUF, 32*1024)//設(shè)置發(fā)送緩沖區(qū)數(shù)據(jù)大小
        .option(ChannelOption.SO_RCVBUF, 32*1024)//設(shè)置接收緩沖區(qū)數(shù)據(jù)大小
        .childOption(ChannelOption.SO_KEEPALIVE, true)//保持長連接
        .childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //通道的初始化,數(shù)據(jù)傳輸過來進行攔截及執(zhí)行
                ch.pipeline().addLast(new ServerHandler());
                
            }
        });
        ChannelFuture f = serverBootstrap.bind(8888).sync();//綁定端口啟動服務(wù)
        f.channel().closeFuture().sync();
        work.shutdownGracefully();
        boss.shutdownGracefully();


    }
    

}

接下來在看數(shù)據(jù)攔截的handler,這個里邊主要是進行數(shù)據(jù)的處理。

package com.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter{
    
    /**
     * 通道激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("數(shù)據(jù)激活");
    }
    
    /**
     * 通道數(shù)據(jù)讀取
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        byte [] by = new byte [in.readableBytes()];
        in.readBytes(by);
        String body=new String(by,"utf-8");
        System.out.println("服務(wù)器收到數(shù)據(jù):"+body);
        
        String response="進行返回給客戶端的響應(yīng)"+body;
        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("數(shù)據(jù)讀取完畢");
    }
}

server端完成之后,接下來看客戶端client,client代碼和server端有點類似

package com.netty.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {
    
    public static void main(String[] args) throws Exception {
        //server端不需要接收連接所有只用一個work來處理連接就可以。
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ClientHandler());

                }
            });

            //連接
            ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
            f.channel().writeAndFlush(Unpooled.copiedBuffer("hello word".getBytes()));
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}

client的handler處理攔截數(shù)據(jù),用來接收服務(wù)端返回的響應(yīng)

package com.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }
    
    /**
     * 通道數(shù)據(jù)讀取
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        byte [] by = new byte [in.readableBytes()];
        in.readBytes(by);
        String body=new String(by,"utf-8");
        System.out.println("接收服務(wù)器端返回信息:"+body);
        
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("接收返回信息完成");
    }
}

netty的helloworld就OK了,超級簡單吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • netty常用API學(xué)習(xí) netty簡介 Netty是基于Java NIO的網(wǎng)絡(luò)應(yīng)用框架. Netty是一個NIO...
    花丶小偉閱讀 6,118評論 0 20
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,812評論 25 709
  • 今天,哦不,昨晚我在看小美好的時候,你望了眼說了句:你們愛帥哥就像男人愛車一樣! 聽到這句話,我是想辯駁的,但是我...
    肥婉閱讀 391評論 0 0
  • 點這里,音樂和文章更配哦~ 去年圣誕節(jié),送給自己一臺kindle,有人說,你買這個,浪費錢,手機一樣可以看。今年圣...
    邢姑娘閱讀 2,456評論 4 0

友情鏈接更多精彩內(nèi)容