何时须要重连呢? 1. 启动的时候,没有成功链接 2. 运行过程当中,链接断掉bootstrap
对第一种状况的解决方法: 实现ChannelFutureListener用来监测是否链接成功,不成功的话重试ide
public class ReConnectionListener implements ChannelFutureListener { private Client client; private int port; private String host; public ReConnectionListener(){ this.client = client; } @Override public void operationComplete(ChannelFuture future) throws Exception { if(!future.isSuccess()){ final EventLoop loop = future.channel().eventLoop(); loop.schedule(new Runnable() { @Override public void run() { try { client.run(port, host); // 这里大意就是从新调用那个链接的过程 } catch (Exception e) { } } }, 1, TimeUnit.SECONDS); } }
对第二种状况的解决办法是: 在一个handler里,oop
public class ReConnectionHandler extends ChannelHandlerAdapter{ private Client client; public ReConnectionHandler(Client client){ this.client = client; } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { final EventLoop eventLoop = ctx.channel().eventLoop(); eventLoop.schedule(new Runnable() { @Override public void run() { try { client.run(); } catch (Exception e) { e.printStackTrace(); } } }, 1, TimeUnit.SECONDS); super.channelInactive(ctx); } }
ReadTimeoutHandlerthis
WriteTimeoutHandlercode
IdleStateHandler( int readerIdleTimeSeconds,int writerIdleTimeSeconds, int allIdleTimeSeconds)事件
ReadTimeoutHandler 和 WriteTimeoutHandler 是读写超时Handler,只有一个参数的构造方法能够穿进去一个秒数,意味着,若是读写事件超过 指定的秒数,就会抛出异常.传到下一个handler的exceptionCaught方法里ip
IdleStateHandler 是什么意思呢 是空闲事件Handler 能够指定一个写空闲,读空闲, 若是超过指定的时间没有读写就会抛出异常 用这个Handler能够实现心跳检测,it
/ An example that sends a ping message when there is no outbound traffic // for 30 seconds. The connection is closed when there is no inbound traffic // for 60 seconds. public class MyChannelInitializer extends ChannelInitializer<Channel> { @Override public void initChannel(Channel channel) { channel.pipeline().addLast("idleStateHandler", new IdleStateHandler(60, 30, 0)); channel.pipeline().addLast("myHandler", new MyHandler()); } } // Handler should handle the IdleStateEvent triggered by IdleStateHandler. public class MyHandler extends ChannelHandlerAdapter { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { ctx.close(); } else if (e.state() == IdleState.WRITER_IDLE) { ctx.writeAndFlush(new PingMessage()); } } } } ServerBootstrap bootstrap = ...; ... bootstrap.childHandler(new MyChannelInitializer());