Hos*_*ein 5 java multithreading netty
我有一个问题,关于如何在创建TCP服务器套接字时将主线程恢复到Netty中.
在下面取自代码在这里,"你好你好"永远不会被写入输出作为启动服务器,等待在这条线螺纹: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");
}
Run Code Online (Sandbox Code Playgroud)
您无需等待近期。这只是在教程中完成的,以使事件循环组正确关闭。
您可以从程序中删除f.channel().closeFuture().sync();和group.shutdownGracefully().sync();行以使其非阻塞。
确保在关闭主程序时调用f.channel().close(), thenf.channel().closeFuture().sync()和finally以确保 Netty 堆栈正确停止group.shutdownGracefully().sync();
| 归档时间: |
|
| 查看次数: |
710 次 |
| 最近记录: |