(点击
上方公众号
,可快速关注)
来源:鸟窝 ,
colobu.com/2015/08/14/netty-tcp-client-with-reconnect-handling/
如有好文章投稿,请点击 → 这里了解详情
当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连。
Netty Client有两种情况下需要重连:
-
Netty Client启动的时候需要重连
-
在程序运行中连接断掉需要重连。
对于第一种情况,Netty的作者在stackoverflow上给出了解决方案,
https://stackoverflow.com/questions/19739054/whats-the-best-way-to-reconnect-after-connection-closed-in-netty
对于第二种情况,Netty的例子uptime中实现了一种解决方案。
https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java
而Thomas在他的文章中提供了这两种方式的实现的例子。
实现ChannelFutureListener 用来启动时监测是否连接成功,不成功的话重试:
public class Client
{
private EventLoopGroup loop = new NioEventLoopGroup();
public static void main( String[] args )
{
new Client().run();
}
public Bootstrap createBootstrap(Bootstrap bootstrap, EventLoopGroup eventLoop) {
if (bootstrap != null) {
final MyInboundHandler handler = new MyInboundHandler(this);
bootstrap.group(eventLoop);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new ChannelInitializer
() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(handler);
}
});
bootstrap.remoteAddress("localhost", 8888);
bootstrap.connect().addListener(new ConnectionListener(this));