关于重连
什么时候需要重连呢? 1. 启动的时候,没有成功连接 2. 运行过程中,连接断掉
对第一种情况的解决方法: 实现ChannelFutureListener用来监测是否连接成功,不成功的话重试
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里,
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);
}
}
提供的Handler.
ReadTimeoutHandler
WriteTimeoutHandler
IdleStateHandler( int readerIdleTimeSeconds,int writerIdleTimeSeconds, int allIdleTimeSeconds)
ReadTimeoutHandler 和 WriteTimeoutHandler 是读写超时Handler,只有一个参数的构造方法可以穿进去一个秒数,意味着,如果读写事件超过 指定的秒数,就会抛出异常.传到下一个handler的exceptionCaught方法里
IdleStateHandler 是什么意思呢 是空闲事件Handler 可以指定一个写空闲,读空闲, 如果超过指定的时间没有读写就会抛出异常 用这个Handler可以实现心跳检测,
/ 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());