不,你做对了。但是,您必须保留对您的Channel
实例的引用。一旦你有了那个通道,只要它是打开的,你就不需要创建另一个引导程序。(如果那是你正在做的。)
这是我在最近的一个项目中使用的:
类 ClientConnection (构造函数)
// 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(字符串主机,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
,但是前者几乎没有在这些代码行之外使用。
注意:您应该只bootstrap.releaseExternalResources();
在应用程序退出时执行一次。就我而言,客户端发送一些文件然后关闭通道并退出。
一旦你有一个连接的Channel
实例,你只需要使用那个,直到你再次关闭它。关闭后,您可以bootstrap
重新创建一个新的Channel
。
就我个人而言,一开始我觉得 Netty 有点难以理解,但是一旦你掌握了它的工作原理,它简直就是 Java 中最好的 NIO 框架。国际海事组织。