不,你做的事情是对的。但是,您必须保留对您的Channel
实例。一旦您拥有该通道,只要它处于打开状态,您就不需要创建另一个引导程序。 (如果这就是你正在做的事情。)
这是我在最近的项目中使用的:
客户端连接类 (构造函数)
// Configure the client.
bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()
)
);
// Set up the pipeline factory.
bootstrap.setPipelineFactory(
new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
// put your handlers here
);
}
}
);
类 ClientConnection.connect(String 主机,int 端口)
if (isConnected()) {
throw new IllegalStateException("already connected");
}
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
channel = future.awaitUninterruptibly().getChannel();
// Wait until the connection is closed or the connection attempt fails.
channel.getCloseFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
new Thread(new Runnable() {
public void run() {
// Shut down thread pools to exit
// (cannot be executed in the same thread pool!
bootstrap.releaseExternalResources();
LOG.log(Level.INFO, "Shutting down");
}
}).start();
}
});
所以,基本上,我只保留一个参考bootstrap
and channel
,但是前者在这些代码行之外几乎不被使用。
Note:你应该只执行bootstrap.releaseExternalResources();
当应用程序退出时一次。就我而言,客户端发送一些文件,然后关闭通道并退出。
一旦您建立了连接Channel
例如,你只需要使用那个,直到你再次关闭它。关闭后,您可以调用bootstrap
创建一个新的Channel
again.
就我个人而言,我觉得 Netty 一开始有点难以理解,但是一旦你掌握了它的工作原理,它就是 Java 中最好的 NIO 框架。国际海事组织。