netty初识

Netty是提供一种异步的事件驱动的网络应用框架,它是一个NIO的C/S的框架,可以开发出高性能,高拓展性的网络服务端和客户端。

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .handler(new LoggingHandler(LogLevel.INFO))
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
                 public void initChannel(SocketChannel ch) {
                     ChannelPipeline p = ch.pipeline();
                     p.addLast(new DiscardServerHandler());
                 }
             });

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(PORT).sync();

            // 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();
    }

以上是最简单的一个netty服务端代码,此处定义了两个event loop。一个称为boss,用来接收连接,另一个称为worker,用来处理boss接收到的连接流量并注册给worker。设置通道类型为NioServerSocketChannel。

这里的核心模块是childHandler,即NIO中的回调部分,它指定了连接后调用的ChannelHandler。参数是ChannelInitializer类型,它是个抽象类,需要实现initChannel方法,在这个方法中设置ChannelHandler。最后指定监听的端口,进行绑定操作,调用sync会阻塞直到服务器完成绑定。

下面是ServerHandler部分,用来处理各种回调的模块。

public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

    //对该方法进行重写,实现自己的逻辑,因为DISCARD,所以这里将收到的字节数组release
    //任何增加引用计数的数据都需要release
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // discard
        ((ByteBuf) msg).release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
原文地址:https://www.cnblogs.com/horo/p/6922480.html