public class IdleStateHandler extends ChannelDuplexHandler
netty 提供了 IdleStateHandler 类来对连接进行心跳检测,防止建立的无用长连接占用系统资源
public IdleStateHandler(
//读的时间
int readerIdleTimeSeconds,
//写的时间
int writerIdleTimeSeconds,
//读和写加在一起的时间
int allIdleTimeSeconds) {
this(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,
TimeUnit.SECONDS);
}
上面构造方法如果默认都给10那么它的意思是 1.如果10秒没有服务端如果没有向客户端读取到任何数据,那么就会触发一个事件2.如果10秒没有客户端如果没有向服务端读取到任何数据,那么就会触发一个事件3.10秒中没有检查到读也没有检查到写就会触发这样的事件
使用例子:
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//心跳检测器
pipeline.addLast(new IdleStateHandler(5,7,10, TimeUnit.SECONDS));
pipeline.addLast(new MyServerHandler());
}
}
public class MyServerHandler extends ChannelInboundHandlerAdapter{
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent){
IdleStateEvent event=(IdleStateEvent)evt;
String eventType=null;
switch (event.state()){
case READER_IDLE:
eventType="读空闲";
break;
case WRITER_IDLE:
eventType="写空闲";
break;
case ALL_IDLE:
eventType="读写都空闲";
break;
}
System.out.println(eventType);
ctx.channel().close();
}
}
}