Netty断线重连

来源:互联网 发布:香港手机网络制式 编辑:程序博客网 时间:2024/04/27 23:51
前面说到了在netty中如何去保持心跳,但是在实际情况中仍然可能发生断线的情况。这个时候我们就需要考虑如何进行断线重连了。


在Netty中保持断线重连我们只需要在client在连接服务器的方法上加上一个监听,当发生断线的时候进行重新连接即可。


 

b.remoteAddress(host, port);b.connect().addListener(new ConnectionListener(this));


具体的监听器类如下:


 

public class ConnectionListener implements ChannelFutureListener {private TimeClient client;public ConnectionListener(TimeClient client) {this.client = client;}@Overridepublic void operationComplete(ChannelFuture future) throws Exception {if (!future.isSuccess()) {System.out.println("Reconnection");final EventLoop eventLoop = future.channel().eventLoop();eventLoop.schedule(new Runnable() {@Overridepublic void run() {client.createBootstrap(new Bootstrap(), eventLoop);}}, 1L, TimeUnit.SECONDS);}}}


这个时候还只是做到了启动服务器的时候自动连接,要做到真正的断线重连还需要在实际的channelhandler中重写public void channelInactive(ChannelHandlerContext ctx)这个方法,当重写这个方法后,如果发生断线情况,这个方法会及时响应,此时会再次主动去连接服务器并启动监听。


客户端程序断线重连打印如下:


ReconnectionReconnectionALL_IDLE ! times : 1ALL_IDLE ! times : 2ReconnectionReconnection


刚开始只启动了客户端,并没有启动服务器,后来启动服务器,最后又再次断开服务器。控制台打印情况如上。
0 0
原创粉丝点击