public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ ServerBootstrap b = new ServerBootstrap(); // 1. 创建ServerBootstrap实例 b.group(bossGroup, workerGroup) // 2. 设置并绑定Reactor线程池 .channel(NioServerSocketChannel.class) // 3. 设置并绑定服务端Channel() .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception{ ch.pipeline() // 4. TCP链路建立时创建ChannelPipeline() .addLast(new EchoServerHandler()); // 5. 添加并设置ChannelHandler() } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); // 6. 绑定监听接口 f.channel().closeFuture().sync(); }finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }?
原文:http://cwind.iteye.com/blog/2223241