Netty 自动重连
from: http://www.dozer.cc/2015/05/netty-auto-reconnect.html
自动重连
用 Netty 写 Client 和 Server 的时候必须要去处理自动重连。
Server 端启动时的错误,要去不断重试。
Client 端不仅要处理启动时的错误,还要处理中途断开连接。
Server 端的处理
和常规的代码相比,Server 端只要处理一个地方即可:
public final class TcpServer { private volatile EventLoopGroup bossGroup; private volatile EventLoopGroup workerGroup; private volatile ServerBootstrap bootstrap; private volatile boolean closed = false; private final int localPort; public TcpServer(int localPort) { this.localPort = localPort; } public void close() { closed = true; bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); System.out.println("Stopped Tcp Server: " + localPort); } public void init() { closed = false; bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //todo: add more handler } }); doBind(); } protected void doBind() { if (closed) { return; } bootstrap.bind(localPort).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { System.out.println("Started Tcp Server: " + localPort); } else { System.out.println("Started Tcp Server Failed: " + localPort); f.channel().eventLoop().schedule(() -> doBind(), 1, TimeUnit.SECONDS); } } }); } }
我们把整个初始化分成了两个部分,第一部分是初始化相关 class,第二部分做真正的监听端口。
这里最特殊的地方就是在调用bind方法后,添加一个listener检查是否成功,如果失败的话,需要调用.channel().eventLoop().schedule()方法,创建一个任务,我这代码设置的是1秒后尝试重新连接。
另外考虑到 server 可以被人为关闭,所以还需要检查当前时候已经关闭。如果不检查的话,你的 server 可能就永远也关不掉了。
Client 端的处理
client 端启动流程差不多,但是需要加一个 handler 来处理连接断开。
public class TcpClient { private volatile EventLoopGroup workerGroup; private volatile Bootstrap bootstrap; private volatile boolean closed = false; private final String remoteHost; private final int remotePort; public TcpClient(String remoteHost, int remotePort) { this.remoteHost = remoteHost; this.remotePort = remotePort; } public void close() { closed = true; workerGroup.shutdownGracefully(); System.out.println("Stopped Tcp Client: " + getServerInfo()); } public void init() { closed = false; workerGroup = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); ctx.channel().eventLoop().schedule(() -> doConnect(), 1, TimeUnit.SECONDS); } }); //todo: add more handler } }); doConnect(); } private void doConnect() { if (closed) { return; } ChannelFuture future = bootstrap.connect(new InetSocketAddress(remoteHost, remotePort)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { System.out.println("Started Tcp Client: " + getServerInfo()); } else { System.out.println("Started Tcp Client Failed: " + getServerInfo()); f.channel().eventLoop().schedule(() -> doConnect(), 1, TimeUnit.SECONDS); } } }); } private String getServerInfo() { return String.format("RemoteHost=%s RemotePort=%d", remotePort, remotePort); } }
可以看到,我们在channelInactive事件中,也创建了一个任务,在1秒后重新连接。
示例代码
大家可以自己跑跑看:
https://github.com/dozer47528/AutoReconnectNettyExample
Netty 自动重连的更多相关文章
- netty系列之:自动重连
目录 简介 使用netty建立连接 自动重连接的原理 模拟自动重连 总结 简介 我们在使用客户端和服务器端连接的过程中,可能会因为各种问题导致客户端和服务器的连接发生中断,遇到这种情况,一般情况下我们 ...
- Netty Client重连实现
from:http://itindex.net/detail/54161-netty-client 当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连 ...
- Netty断线重连
Netty断线重连 最近使用Netty开发一个中转服务,需要一直保持与Server端的连接,网络中断后需要可以自动重连,查询官网资料,实现方案很简单,核心思想是在channelUnregistered ...
- Netty Client 重连实现
当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连.Netty Client有两种情况下需要重连: Netty Client启动的时候需要重连 在程序 ...
- 如何实现Azure虚拟网络中点到站VPN的自动重连
在Windows Azure早期版本中,用户要在某台Azure平台之外的机器与Azure平台内部的机器建立专用连接,可以借助Azure Connect这个功能.当前的Azure版本,已经没有Az ...
- 解读dbcp自动重连那些事---转载
http://agapple.iteye.com/blog/791943 可以后另一篇做对比:http://agapple.iteye.com/blog/772507 同样的内容,不同的描述方式,不一 ...
- PERL DBI 自动重连问题
[root@wx03 mojo]# cat relink.pl use Mojolicious::Lite; use JSON qw/encode_json decode_json/; use Enc ...
- NodeMCU之旅(二):断线自动重连,闪烁连接状态
事件监听器 NodeMCU采用了事件响应的方式.也就是说,只需为事件设置一个回调函数,当事件发生时,回调函数就会被调用. 注册事件监听器 wif.sta.eventMonReg() 开始监听 wifi ...
- 【树莓派】树莓派下WiFi断线自动重连
实现 WiFi 断线自动重连.原理是用 Python 监测网络是否断线,如果断线则重启网络服务. 1.Python 代码 autowifi.py,放在 /home/pi 目录下: #!/usr/bin ...
随机推荐
- VC方法调用顺序
VC1,push VC2  vc2 pop 到vc1  右滑一半,然后取消 vc1 present到vc2  vc2 dismiss到vc1  push和present是不同的.表现在两个vc ...
- Android程序意外Crash后自动重启
1.自定义UncaughtExceptionHandler public class UnCeHandler implements UncaughtExceptionHandler { private ...
- yii2使用多个数据库的案例
作者:白狼 出处:http://www.manks.top/article/yii2_%E5%88%86%E5%BA%93%E5%88%86%E8%A1%A8_config 本文版权归作者,欢迎转载, ...
- Sublime Text插件:HTML-CSS-JS Prettify
该插件依赖到nodejs环境 1.安装 在Sublime Text中,按下Ctrl+Shift+P调出命令面板; 输入install 调出 Install Package 选项并回车; 输入prett ...
- Linux Swap交换分区介绍总结
Swap交换分区概念 什么是Linux swap space呢?我们先来看看下面两段关于Linux swap space的英文介绍资料: Linux divides its physical RA ...
- One to One 的数据库模型设计与NHibernate配置
在数据库模型设计中,最基本的实体关系有三种:一对一.一对多.多对多.关于一对多和多对多使用的情况较多,之前也有过一些讨论,现在来说明一下在数据库中一对一的模型设计. 首先,关系数据库中使用外键来表示一 ...
- 首先,编写一个类ChongZai,该类中有3个重载的方法void print();其次, 再编写一个主类来测试ChongZai类的功能
//计算器 jisuanqi jsq=new jisuanqi(); System., )); System., , )); System.out.println("2.3和4.5 中最大的 ...
- A cost-effective recommender system for taxi drivers
一个针对出租车司机有效花费的推荐系统 摘要 GPS技术和新形式的城市地理学改变了手机服务的形式.比如说,丰富的出租车GPS轨迹使得出做租车领域有新方法.事实上,最近很多工作是在使用出租车GPS轨迹数据 ...
- WIN32 API编程之 透明static
createwindow可以直接创建一个staitc,但这个static是不透明的,如果我们把窗口背景设置为GRAY_BRUSH,则static会很明显的有一个白色背景,一般来说这样肯定很难看. 可以 ...
- 网页中显示pdf
1.<embed width="800" height="600" src="test_pdf.pdf"> </embed ...