publicclassEchoServer{publicstaticvoidmain(String[] args)throws Exception{// (1) 初始化用于Acceptor(接受消息)的主"线程池"以及用于I/O工作的从"线程池";
EventLoopGroup bossGroup =newNioEventLoopGroup();// 处理客户端连接的主线程池
EventLoopGroup workerGroup =newNioEventLoopGroup();// 用于处理I/O的从线程池try{// (2) 初始化ServerBootstrap实例, 此实例是netty服务端应用开发的入口
ServerBootstrap boot =newServerBootstrap();// (3) 通过ServerBootstrap的group方法,设置(1)中初始化的主从"线程池"
boot.group(bossGroup, workerGroup);// (4) 指定通道channel的类型,由于是服务端,故而是NioServerSocketChannel
boot.channel(NioServerSocketChannel.class);// (5) 设置ServerSocketChannel的处理器
boot.handler(newLoggingHandler());// (6) 配置ServerSocketChannel的选项
boot.option(ChannelOption.SO_BACKLOG,128);// (7) 配置子通道也就是SocketChannel的选项
boot.childOption(ChannelOption.SO_KEEPALIVE,true);// (8) 设置子通道也就是SocketChannel的处理器, 其内部是实际业务开发的"主战场"
boot.childHandler(newChannelInitializer<SocketChannel>(){@OverridepublicvoidinitChannel(SocketChannel ch)throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline .addLast(newEchoServerHandler());}});// Bind and start to accept incoming connections.// (9) 绑定并侦听某个端口
ChannelFuture f = boot.bind("127.0.0.1",8089).sync();// (9)// 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().sync();
bossGroup.shutdownGracefully().sync();}}}