翻译网页网址:http://netty.io/wiki/user-guide-for-5.x.html
翻译:
NioEventLoopGroup的实现类可以查看API,http://netty.io/5.0/api/index.html.路径为io.netty.channel.NioEventLoopGroup
翻译:
package io.netty.example.discard; import io.netty.bootstrap.ServerBootstrap; 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.NioServerSocketChannel; /** * Discards any incoming data. */ public class DiscardServer { private int port; public DiscardServer(int port) { this.port = port; } 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(); } } public static void main(String[] args) throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 8080; } new DiscardServer(port).run(); } }
3) 此处我们指明使用NioServerSocketChannel来初始化一个新的Channel来接收传入的连接。
4)此处指定的处理程序通常被一个新的接收渠道使用。ChannelInitializer类是一个指定的处理程序,他被用来帮助用户配置一个新的渠道。大多数状态下当我们通过添加一些处理器(例如:DiscardServerHandler)来实现我们的网络应用想要配置一个新的渠道的ChannelPipeline时需要这样做。当这个应用程序变的复杂时,例如我们最终将增加更多的处理器到这个管道里并且提取匿名类到定层类时很有用处。
5)我们可以设置这个参数,参数是用来指定Channel实现的。这里我们是写一个TCP/IP服务器,所以我们允许设置socket选项,例如:tcpNoDelay或者keepAlive。请查看ChannelOption的apidocs文档和指定ChannelConfig实现来浏览一下支持的ChannelOptions。具体网址为:http://netty.io/5.0/api/io/netty/channel/ChannelConfig.html和http://netty.io/5.0/api/io/netty/channel/ChannelOption.html
6)option() 是针对接收传入链接的NioServerSocketChannel,childOption()是针对被父ServerChannel接收的Channels,此处是NioServerSocketChannel