【发布时间】:2013-02-21 15:42:30
【问题描述】:
在 Netty 中重试连接
我正在构建一个客户端套接字系统。要求是: 首先尝试连接到远程服务器 当第一次尝试失败时继续尝试,直到服务器在线。
我想知道netty中是否有这样的功能可以做到这一点,或者我怎样才能最好地解决这个问题。
非常感谢
这是我正在努力解决的代码 sn-p:
protected void connect() throws Exception {
this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Configure the event pipeline factory.
bootstrap.setPipelineFactory(new SmpPipelineFactory());
bootstrap.setOption("writeBufferHighWaterMark", 10 * 64 * 1024);
bootstrap.setOption("sendBufferSize", 1048576);
bootstrap.setOption("receiveBufferSize", 1048576);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
// Make a new connection.
final ChannelFuture connectFuture = bootstrap
.connect(new InetSocketAddress(config.getRemoteAddr(), config
.getRemotePort()));
channel = connectFuture.getChannel();
connectFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future)
throws Exception {
if (connectFuture.isSuccess()) {
// Connection attempt succeeded:
// Begin to accept incoming traffic.
channel.setReadable(true);
} else {
// Close the connection if the connection attempt has
// failed.
channel.close();
logger.info("Unable to Connect to the Remote Socket server");
}
}
});
}
【问题讨论】:
-
没有内置功能可以做到这一点,你需要自己做。
-
@BrianRoach:你能指导我实现这样的要求吗,因为我不是netty的极客。
-
不幸的是,这远远超出了 StackOverflow 的答案范围。使用 netty 编写客户端并不容易,需要对框架有相当多的了解。要为您指明正确的方向,您需要查看
Channel.closeFuture()- 您需要注册ChannelFutureListener并在未来完成时收到通知(意味着频道已关闭)。 -
实际上,在初始连接尝试中,您使用引导程序的
connect()调用返回的Future- 我可以在这里合理地回答 - 秒。 -
@BrianRoach:谢谢。我做了连接和未来。这有助于我检查连接是否成功。问题是当服务器可用时如何重试失败,直到我连接。