最近使用Netty开发一个中转服务,需要一直保持与Server端的连接,网络中断后需要可以自动重连,查询官网资料,实现方案很简单,核心思想是在channelUnregistered钩子函数里执行重连。
需要把configureBootstrap重构为一个函数,方便后续复用
EventLoopGroup group = new NioEventLoopGroup();
private volatile Bootstrap bootstrap;
public void init(String host, int port) throws RobotException {
this.serverIp = host;
this.serverPort = port;
try {
// 创建并初始化 Netty 客户端 Bootstrap 对象
bootstrap = configureBootstrap(new Bootstrap(),group);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
doConnect(bootstrap);
}
catch(Exception ex){
ex.printStackTrace();
throw new RobotException("connect remote control server error!",ex.getCause());
}
}
Bootstrap configureBootstrap(Bootstrap b, EventLoopGroup g) {
b.group(g).channel(NioSocketChannel.class)
.remoteAddress(serverIp, serverPort)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
// 编解码器
pipeline.addLast(protoCodec);
// 请求处理
pipeline.addLast(RobotClient.this);
}
});
return b;
}
void doConnect(Bootstrap b) {
try {
ChannelFuture future = b.connect();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("Started Tcp Client: " + serverIp);
} else {
System.out.println("Started Tcp Client Failed: ");
}
if (future.cause() != null) {
future.cause().printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
断线重连
来看断线重连的关键代码:
@ChannelHandler.Sharable
public class RobotClient extends SimpleChannelInboundHandler<RobotProto> {
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// 状态重置
isConnected = false;
this.serverStatus = -1;
final EventLoop loop = ctx.channel().eventLoop();
loop.schedule(new Runnable() {
@Override
public void run() {
doConnect(configureBootstrap(new Bootstrap(), loop));
}
}, 1, TimeUnit.SECONDS);
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有