Netty 客户端断线重连
Posted victorbu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Netty 客户端断线重连相关的知识,希望对你有一定的参考价值。
client 关闭后会执行 finally 代码块,可以在这里可以进行重连操作
public class NettyClient implements Runnable {
private final String host;
private final int port;
private final int reconnectSleepSeconds;
public NettyClient(String host, int port, int reconnectSleepSeconds){
this.host = host;
this.port = port;
this.reconnectSleepSeconds = reconnectSleepSeconds;
}
@Override
public void run() {
connect();
}
private void connect(){
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NiosocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// TODO: 添加 Handler
}
});
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
} catch (Exception e){
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
try {
TimeUnit.SECONDS.sleep(reconnectSleepSeconds);
connect(); // 断线重连
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
以上是关于Netty 客户端断线重连的主要内容,如果未能解决你的问题,请参考以下文章