服务端挂了或者主动拒绝客户端的连接后,客户端不死心,每15秒重连试试,3次都不行就算了。修改下之前的客户端引导类(NettyClient,参见netty5心跳与业务消息分发实例),新增两个成员变量,在connect连接方法里的finally加入重连操作:

    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
private AtomicInteger reconnetTimes = new AtomicInteger(0); public void connect(int port, String host) throws Exception {
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new NettyMessageDecoder());
channel.pipeline().addLast(new NettyMessageEncoder());
channel.pipeline().addLast(new ControlClientHandler());
channel.pipeline().addLast(new HeartBeatClientHandler());
// channel.pipeline().addLast(new NettyClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} finally { group.shutdownGracefully(); // 所有资源释放完成之后,清空资源,再次发起重连操作
executorService.execute(new Runnable() {
@Override
public void run() { // 重连3次均失败,关闭线程池
if (reconnetTimes.get() > 3) {
log.error("reconnect times > 3.");
executorService.shutdown();
} // 每15秒重连一次
try {
TimeUnit.SECONDS.sleep(15);
try {
// 发起重连操作,连接成功后将阻塞
connect(port, "127.0.0.1");
} catch (Exception e) {
reconnetTimes.getAndIncrement();
log.error("client try to reconnect failed, error : {}", e.getMessage());
}
} catch (InterruptedException e) {
reconnetTimes.incrementAndGet();
log.error("client try to reconnect failed, error : {}", e.getMessage());
} }
});
}
}

  不起服务端,我们只起客户端,输出如下:

Exception in thread "main" java.net.ConnectException: Connection refused: no further information: /127.0.0.1:9911
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:223)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:276)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:531)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)
17:02:02.968 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:19.013 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:35.063 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:51.112 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:51.112 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - reconnect times > 3.
17:03:07.140 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@16c59706 rejected from java.util.concurrent.ScheduledThreadPoolExecutor@6fa6a4f0[Shutting down, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 4] Process finished with exit code 1

  如果3次重连过程中你把服务端起了,那么客户端就会连上去:

Exception in thread "main" java.net.ConnectException: Connection refused: no further information: /127.0.0.1:9911
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:223)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:276)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:531)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)
17:06:40.171 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:06:56.219 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:07:11.297 [nioEventLoopGroup-4-0] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetectionLevel: simple
17:07:11.304 [nioEventLoopGroup-4-0] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacity: 262144
17:07:11.366 [nioEventLoopGroup-4-0] INFO com.wlf.netty.nettyclient.handler.HeartBeatClientHandler - [client] control response is OK, header : Header{delimiter=-1410399999, length=8, type=0, reserved=0}. sid : 63, interval : 5000
17:07:16.412 [nioEventLoopGroup-4-0] INFO com.wlf.netty.nettyclient.handler.HeartBeatClientHandler - [client] Client send heart beat message to server : ----> NettyMessage{header=Header{delimiter=-1410399999, length=4, type=3, reserved=0}, data=[B@682470ef}
17:07:16.412 [nioEventLoopGroup-4-0] INFO com.wlf.netty.nettyclient.handler.HeartBeatClientHandler - [client] Client send business message to server : ----> NettyMessage{header=Header{delimiter=-1410399999, length=161800, type=1, reserved=0}, data=[B@41bd2db4}

netty5客户端监测服务端断连后重连的更多相关文章

  1. Android-socket服务端断重启后,android客户端自动重连

    今天研究这个问题搞了整整一天啊!终于出来了,不过我没有多大的成就感,为什么呢?因为这不是我的劳动成果.同样的问题,我却没想出来!心塞的很啊…… 不过还是要给大家分享一下,希望给大家带来帮助! 先声明一 ...

  2. Consul的一个更新:服务端节点故障后重连

    研究了一段时间Consul,想写个攻略来着,但太赖了而且表达能力非正常人...今天发现HashiCorp果然接纳大众意见改了点东西.. 场景是: 假如Consul集群内有三个Server Node 时 ...

  3. .net remoting 客户端与服务端绑定事件,一部电脑当服务器,另一部当客户端,发布后没法接收远程错误信息。

    可以是用下面代码抛出远程错误,客户端和服务端都要设置,因为服务端事件回调时角色变成了远程客户端了. RemotingConfiguration.CustomErrorsMode = CustomErr ...

  4. FastSocket学习笔记~再说客户端与服务端的组成

    废话多说 很久之前,我写过几篇FastSocket的文章,基本属于使用的方法,而缺乏对概念的总结讲解,而本讲就是弥补一下上几讲的不足,将核心的模块再说说,再谈谈,再聊聊! 首先FastSocket由C ...

  5. SignalR 实现web浏览器客户端与服务端的推送功能

    SignalR 是一个集成的客户端与服务器库,基于浏览器的客户端和基于 ASP.NET 的服务器组件可以借助它来进行双向多步对话. 换句话说,该对话可不受限制地进行单个无状态请求/响应数据交换:它将继 ...

  6. Fresco 源码分析(二) Fresco客户端与服务端交互(3) 前后台打通

    4.2.1.2.4 PipelineDraweeControllerBuilder.obtainController()源码分析 续 上节中我们提到两个核心的步骤 obtainDataSourceSu ...

  7. Asp.Net MVC 模型验证详解-实现客户端、服务端双重验证

    概要 在asp.net webform开发中经常会对用户提交输入的信息进行校验,一般为了安全起见大家都会在客户端进行Javascript(利于交互).服务端双重校验(安全).书写校验代码是一个繁琐的过 ...

  8. Java实现UDP之Echo客户端和服务端

    Java实现UDP之Echo客户端和服务端 代码内容 采用UDP协议编写服务器端代码(端口任意) 编写客户机的代码访问该端口 客户机按行输入 服务器将收到的字符流和接收到的时间输出在服务器consol ...

  9. Java实现TCP之Echo客户端和服务端

    Java实现TCP之Echo客户端和服务端 代码内容 采用TCP协议编写服务器端代码(端口任意) 编写客户机的代码访问该端口 客户机按行输入 服务器将收到的字符流和接收到的时间输出在服务器consol ...

随机推荐

  1. P1392 取数[堆]

    题目描述 在一个n行m列的数阵中,你须在每一行取一个数(共n个数),并将它们相加得到一个和.对于给定的数阵,请你输出和前k小的取数方法. 解析 写这题完全自闭. 根本没联想起远古时期做的 P1631 ...

  2. 行为型模式(三) 迭代器模式(Iterator)

    一.动机(Motivate) 在软件构建过程中,集合对象内部结构常常变化各异.但对于这些集合对象,我们希望在不暴露其内部结构的同时,可以让外部客户代码透明地访问其中包含的元素:同时这种"透明 ...

  3. tcp三次握手,四次挥手的形象类比图

  4. ascii、unicode、utf-8、gbk 区别?

    发展史: https://www.cnblogs.com/houxt/p/11250878.html python2内容进行编码(默认ascii),而python3对内容进行编码的默认为utf-8. ...

  5. Codeforces Round #604 (Div. 2) B. Beautiful Numbers

    链接: https://codeforces.com/contest/1265/problem/B 题意: You are given a permutation p=[p1,p2,-,pn] of ...

  6. CSS字体图标

    一.什么是字体图标: 1. 字体图标可以和图片一样改变透明度,旋转度,等等 2.本质是文字,可以改变大小颜色等等比较适用于移动端 总结;图标字体具有矢量效果,放大缩小不失真,而且可以使用CSS任意更改 ...

  7. Cogs 452. Nim游戏!(博弈)

    Nim游戏! ★ 输入文件:nim!.in 输出文件:nim!.out 简单对比 时间限制:1 s 内存限制:128 MB 甲,乙两个人玩Nim取石子游戏. nim游戏的规则是这样的:地上有n堆石子( ...

  8. 一个 Object.assign 的误解

    mozilla中对 Object.assign 的解释如下地址: mozilla 其中有说到 注意, Object.assign 会跳过那些值为 null 或 undefined 的源对象. 一直以为 ...

  9. 一步一步跟我学ImGui.第一讲.配置OpenGl2+ImGui环境

    目录 搭建ImGui例子中的第一个OpenGl2环境 一丶搭建OpenGL2环境 1.下载GLFW库 2.解压GLFW库. 3.将GLFW库拷贝到你的工程文件下. 4.配置到Vs2013中. 5.测试 ...

  10. npropress进度条插件的使用

    官网下载地址:http://ricostacruz.com/nprogress/ npropress.css /* Make clicks pass-through */ #nprogress { p ...