当客户端断开连接的时候,服务端需要及时的将这个连接关闭,以释放资源。所以通常每隔一定时间,客户端会向服务端发送心跳消息,证明自己的存在,否则服务端就认为客户端已经断开。
IdleStateHandler
IdleStateHandler可用来检测心跳消息,三个参数分别为,读空闲时间、写空闲时间、读或写空闲,最后参数为时间单位,这里是分钟。即3分钟内没有读取到任何消息,即触发心跳超时事件。两个0表示禁用写空闲和读写空闲。
ch.pipeline().addLast("idleStateHandler",new IdleStateHandler(3, 0,0, TimeUnit.MINUTES));
ch.pipeline().addLast("heartbeatHandler", new HeartbeatHandler());//自定义Handler事件
超时事件
IdleStateHandler触发超时事件后,会传播给下一个Handler,即如下的自定义Handler,在userEventTriggered中捕捉事件。
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {//是否是超时事件
IdleStateEvent ide = (IdleStateEvent)evt;
if(ide.state() == IdleState.READER_IDLE){//读心跳超时
ctx.channel().close();//关闭连接
}
} else {//其他事件,向后传播,交给其他Handler处理
super.userEventTriggered(ctx, evt);
}