java - 在 Netty ServerSocket 中获取主线程

标签 java multithreading netty

我有一个关于在创建 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");
}

最佳答案

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

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

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

关于java - 在 Netty ServerSocket 中获取主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36134152/

相关文章:

java - 了解多线程

multithreading - 在为 Runnable 提供 lambda 时,为什么我不必重写 run 方法?

.net - Rx .NET : Filter observable until task is done

gradle - Apache Spark 和 gRPC

java - javapan最大websocket帧大小?

java - 实例化二叉树中的根的问题

java - PlayFramework 2.x Ebean 查询匹配集合中的 Manytomany 属性

c# - 接口(interface)的 C# "explicit implementation"是否存在于 Java 中?

java - 当我使用 ReplaySubject 中的 Observable 时阻止 ChannelHandlerContext

Java无限长循环