channelInactive 进行重连 (我是直接 new 了一个线程去重连)
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- System.out.println("客户端断开了连接, time:" + new Date().toLocaleString());
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- new MyClient05("127.0.0.1", 9001).start();
- System.out.println("客户端重新连接了服务端 time:" + new Date().toLocaleString());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
测试方法:
1. 可以直接通过上面的心跳机制断开连接后, 客户端的 channelInactive 检测到断开会自动执行重连
测试结果:
服务端:
------
心跳检测触发了事件, object: , time: io.netty.handler.timeout.IdleStateEvent@ab81552019-11-8 16:43:12
服务端监测到了读取超时
心跳检测触发了事件, object: , time: io.netty.handler.timeout.IdleStateEvent@15192622019-11-8 16:43:17
服务端监测到了读取超时
心跳检测触发了事件, object: , time: io.netty.handler.timeout.IdleStateEvent@15192622019-11-8 16:43:22
服务端监测到了读取超时
客户端还在?? 已经 3 次检测没有访问了, 我要断开了哦!!!
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler close
信息: [id: 0x6bfc0d90, L:/192.168.0.118:9001 - R:/192.168.0.118:51031] CLOSE
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler channelInactive
信息: [id: 0x6bfc0d90, L:/192.168.0.118:9001 ! R:/192.168.0.118:51031] INACTIVE
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler channelUnregistered
信息: [id: 0x6bfc0d90, L:/192.168.0.118:9001 ! R:/192.168.0.118:51031] UNREGISTERED
服务端与客户端断开了连接, time: 2019-11-8 16:43:22
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler channelRegistered
信息: [id: 0xbcb2ec62, L:/127.0.0.1:9001 - R:/127.0.0.1:51061] REGISTERED
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler channelActive
信息: [id: 0xbcb2ec62, L:/127.0.0.1:9001 - R:/127.0.0.1:51061] ACTIVE
myServerHandler is active, time: 2019-11-8 16:43:22
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler write
信息: [id: 0xbcb2ec62, L:/127.0.0.1:9001 - R:/127.0.0.1:51061] WRITE: 成功连接服务端, 当前时间: 2019-11-8 16:43:22
十一月 08, 2019 4:43:22 下午 io.netty.handler.logging.LoggingHandler flush
信息: [id: 0xbcb2ec62, L:/127.0.0.1:9001 - R:/127.0.0.1:51061] FLUSH
十一月 08, 2019 4:43:26 下午 io.netty.handler.logging.LoggingHandler channelReadComplete
-------------------------------------------------------------------------------------
客户端:
-------
当前已连接
客户端与服务端建立了连接 time: 2019-11-8 16:43:07
客户端接收到了服务的响应的数据 msg: 成功连接服务端, 当前时间: 2019-11-8 16:43:07, time: 2019-11-8 16:43:07
客户端断开了连接, time: 2019-11-8 16:43:22
当前已连接
客户端与服务端建立了连接 time: 2019-11-8 16:43:22
客户端接收到了服务的响应的数据 msg: 成功连接服务端, 当前时间: 2019-11-8 16:43:22, time: 2019-11-8 16:43:22
来源: https://www.cnblogs.com/hetangyuese/p/11821519.html