一.原理与源码阅读
Netty4.0提供了一个类,名为IdleStateHandler,这个类可以对三种类型的心跳检测。
....
public IdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
this((long)readerIdleTimeSeconds, (long)writerIdleTimeSeconds, (long)allIdleTimeSeconds, TimeUnit.SECONDS);
}
....
前三个的参数解释如下:
1)readerIdleTime:为读超时时间(即测试端一定时间内未接受到被测试端消息)
2)writerIdleTime:为写超时时间(即测试端一定时间内向被测试端发送消息)
3)allIdleTime:所有类型的超时时间
我们在pipeLine中加入了IdleSateHandler,第一个参数是readerIdleTimeSeconds,数值为5,那么,在服务器端会每隔5秒来检查一下channelRead方法被调用的情况,如果在5秒内pipeLine中的channelRead方法都没有被触发,就会调用userEventTriggered方法。
下面我们看一下源码是怎么调用的...
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.initialize(ctx);
super.channelActive(ctx);
}
首先是channelActive,在channel激活时,会触发初始化,下面是初始化的方法
private void initialize(ChannelHandlerContext ctx) {
switch(this.state) {
case 1:
case 2:
return;
default:
this.state = 1;
this.initOutputChanged(ctx);
this.lastReadTime = this.lastWriteTime = this.ticksInNanos();
if (this.readerIdleTimeNanos > 0L) {
//注意这里
this.readerIdleTimeout = this.schedule(ctx, new IdleStateHandler.ReaderIdleTimeoutTask(ctx), this.rea