我有一个关于在创建 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/