【问题标题】:What is the difference between ServerBootstrap.option() and ServerBootstrap.childOption() in netty 4.xNetty 4.x 中的 ServerBootstrap.option() 和 ServerBootstrap.childOption() 有什么区别
【发布时间】:2016-02-19 02:39:00
【问题描述】:

根据文档New and noteworthy in 4.0,netty4提供了新的引导API,文档给出了如下代码示例:

public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .option(ChannelOption.SO_BACKLOG, 100)
         .localAddress(8080)
         .childOption(ChannelOption.TCP_NODELAY, true)
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ch.pipeline().addLast(handler1, handler2, ...);
             }
         });

        // Start the server.
        ChannelFuture f = b.bind().sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

        // Wait until all threads are terminated.
        bossGroup.terminationFuture().sync();
        workerGroup.terminationFuture().sync();
    }
}

代码使用ServerBootStrap.option设置ChannelOption.SO_BACKLOG,然后使用ServerBootStrap.childOption设置ChannelOption.TCP_NODELAY

ServerBootStrap.optionServerBootStrap.childOption 有什么区别?我怎么知道哪个选项应该是option,哪个应该是childOption

【问题讨论】:

    标签: java netty


    【解决方案1】:

    ServerBootStrap.option 和有什么区别 ServerBootStrap.childOption?

    我们使用ServerBootStrap.option 设置的参数适用于新创建的 ServerChannel 的 ChannelConfig,即侦听并接受客户端连接的服务器套接字。当调用 bind() 或 connect() 方法时,这些选项将在服务器通道上设置。此频道是每台服务器一个。

    ServerBootStrap.childOption 适用于频道的 channelConfig,一旦 serverChannel 接受客户端连接,就会创建该频道。此通道是每个客户端(或每个客户端套接字)的。

    所以ServerBootStrap.option 参数适用于正在侦听连接的服务器套接字(服务器通道),ServerBootStrap.childOption 参数适用于服务器套接字接受连接后创建的套接字。

    同样可以扩展到ServerBootstrap 类中的attrchildAttrhandlerchildHandler 方法。

    我怎么知道哪个选项应该是选项,哪个选项应该是 一个子选项?

    支持哪些 ChannelOptions 取决于我们使用的通道类型。 您可以参考您正在使用的 ChannelConfig 的 API 文档。 http://netty.io/4.0/api/io/netty/channel/ChannelConfig.html 及其子类。您应该为每个 ChannelConfig 找到 Available Options 部分。

    【讨论】:

    【解决方案2】:

    也就是说,ServerBootStrap.option 与 bossGroup 一起使用,ServerBootStrap.childOption 与 workerGroup 一起使用。

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 1970-01-01
      • 2019-09-23
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多