写个简单点,比较小白的文档,言语比较接地气

Netty是什么?
NIO的高层封装,NIO很难写,所以有了Netty,方便异步的操作

service的主要代码片段

public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new DiscardServerHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
    
            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)
    
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

按照代码顺序解释如下

(1) EventLoopGroup bossGroup = new NioEventLoopGroup();
事件循环队列,用来接受或发送事件。大家可以把他想象成邮局,消息都要先到邮局,然后再分发出去,邮局维护了一个循环队列,用来不断的收信和发信。

(2)ServerBootstrap b = new ServerBootstrap();
启动服务

(3) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
开启了一个通道,这个通道是用来接受连接请求的,管道大家都知道吧,IO里也有,NIO中也有,一切Java中到处都是管道

(4).childHandler(new ChannelInitializer<SocketChannel>()
这个handler是用来表示响应什么样的事件的,比如我们这里DiscardServerHandler,随着程序的复杂,你会加上更多的handle,handler是具体干事的人

(5).option(ChannelOption.SO_BACKLOG, 128)
channel的配置参数,具体可以查手册

(6).childOption(ChannelOption.SO_KEEPALIVE, true);
option()是 NioServerSocketChannel的配置,childOption()是被parent ServerChannel接受的channel,这里就指的是NioServerSocketChannel

(7)ChannelFuture f = b.bind(port).sync();
绑定端口并开始

再看看我们主要进行事件处理的handle

public class DiscardServerHandler extends ChannelHandlerAdapter { // (1)

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        // Discard the received data silently.
        ((ByteBuf) msg).release(); // (3)
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}

(1)DiscardServerHandler extends ChannelHandlerAdapter
表示:俺是具体干事的人

(2)我们overrider了 channelRead(),用来读取接受到的信息

(3)异常处理,懂的...


方老司
2k 声望224 粉丝

教育皆祸害,[链接]