服务端挂了或者主动拒绝客户端的连接后,客户端不死心,每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. 四.Protobuf3 缺省值

    解析消息时,如果编码消息不包含特定的单数元素,则解析对象中的相应字段将设置为该字段的默认值.这些默认值是特定于类型的: 对于字符串,默认值为空字符串. 对于字节,默认值为空字节. 对于布尔,默认值为f ...

  2. GITHUB下载源码

    从昨天开始就想着从GitHub上下载一个开源的Vue的实战项目,希望能从中学习更多的Vue的实用内容,结果搞了半天好不容易下载了,不知道怎么弄.然而,今天终于成功了,激动地我赶紧来记录一下. 如何从G ...

  3. 关闭win10 任务栏窗口预览的步骤:

    win10虽好,但是总有不利于使用的反人类设计,好在可以设置,这也是比较好了的, 作为开发人员,经常会开好几个窗口,但是win10的预览很不好,设计的就是娱乐用途一般,因此必须是把他关了 一下步骤亲自 ...

  4. Django --- 常用字段及参数

    1 ORM字段 AutoField int自增列,必须填入参数 primary_key=True.当model中如果没有自增列,则自动会创建一个列名为id的列. IntegerField 一个整数类型 ...

  5. bzoj 2480——扩展BSGS

    题意 给定 $a,b$ 和模数 $p$,求整数 $x$ 满足 $a^x \equiv  b(mod \ p)$,不保证 $a,p$ 互质. (好像是权限题,可见洛谷P4195 分析 之前讲过,可以通过 ...

  6. Mybatis下Oracle插入新增返回主键id

    具体xml中sql是这样写,但是要注意SQ_USER.Nextval,SQ_USER是序列,你要替换下自己要进行操作的表的序列,不知道序列的话,可以sql查找下,select * from user_ ...

  7. Java基础学习【字符串倒序输出+排序】

    字符串逆序输出 import java.util.*; public class Main{ public static void main(String [] args) { //字符串逆序输出 S ...

  8. learning java Objects.requireNonNull 当传入参数为null时,该方法返回参数本身

    System.out.println(Objects.hashCode(obj)); System.out.println(Objects.toString(obj)); System.out.pri ...

  9. C语言利用fgetc复制拷贝文件内容

    #include <stdio.h> #include <stdlib.h> //文件的内容复制 int main(int a,char *argv[]){ if(a!=3){ ...

  10. make和rpm的编译、打包总结

    1  make工具使用 1.1 makefile基本规则 Make工具最主要也是最基本的功能就是通过makefile文件来描述源程序之间的相互关系并自动维护编译工作. Makefile的规则: tar ...