【发布时间】: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