【问题标题】:Getting the main thread back in Netty ServerSocket在 Netty ServerSocket 中获取主线程
【发布时间】:2016-03-22 02:25:00
【问题描述】:

我有一个问题,关于如何在创建 TCP 服务器套接字时让主线程回到 Netty 中。

在以下取自here 的代码中,“Hello Hello”永远不会写在输出中,因为启动服务器的线程会在这一行等待:f.channel().closeFuture().sync();。在这种情况下,我是否需要创建一个单独的线程来取回主线程,或者在 Netty 中是否有任何方法可以让我这样做(让 TCP 在后台运行时取回主线程)?

public void start() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(group)
         .channel(NioServerSocketChannel.class)
         .localAddress(new InetSocketAddress(port))
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) 
                 throws Exception {
                 ch.pipeline().addLast(
                         new EchoServerHandler());
             }
         });

        ChannelFuture f = b.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println(
                "Usage: " + EchoServer.class.getSimpleName() +
                " <port>");
        return;
    }
    int port = Integer.parseInt(args[0]);
    new EchoServer(port).start();
    System.out.println("Hello Hello");
}

【问题讨论】:

    标签: java multithreading netty


    【解决方案1】:

    您无需等待关闭的未来。这仅在教程中完成以使事件循环组正确关闭。

    您可以从程序中删除f.channel().closeFuture().sync();group.shutdownGracefully().sync(); 行以使其成为非阻塞。

    确保在关闭主程序时调用f.channel().close(),然后是f.channel().closeFuture().sync(),最后是group.shutdownGracefully().sync();,以确保正确停止Netty堆栈

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2012-05-21
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多