当前位置:   article > 正文

Netty (8)-心跳机制_heartbeathandler

heartbeathandler

当客户端断开连接的时候,服务端需要及时的将这个连接关闭,以释放资源。所以通常每隔一定时间,客户端会向服务端发送心跳消息,证明自己的存在,否则服务端就认为客户端已经断开。

IdleStateHandler

IdleStateHandler可用来检测心跳消息,三个参数分别为,读空闲时间、写空闲时间、读或写空闲,最后参数为时间单位,这里是分钟。即3分钟内没有读取到任何消息,即触发心跳超时事件。两个0表示禁用写空闲和读写空闲。

  1. ch.pipeline().addLast("idleStateHandler",new IdleStateHandler(3, 0,0, TimeUnit.MINUTES));
  2. ch.pipeline().addLast("heartbeatHandler", new HeartbeatHandler());//自定义Handler事件

超时事件

IdleStateHandler触发超时事件后,会传播给下一个Handler,即如下的自定义Handler,在userEventTriggered中捕捉事件。

  1. public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
  2. @Override
  3. public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  4. if (evt instanceof IdleStateEvent) {//是否是超时事件
  5. IdleStateEvent ide = (IdleStateEvent)evt;
  6. if(ide.state() == IdleState.READER_IDLE){//读心跳超时
  7. ctx.channel().close();//关闭连接
  8. }
  9. } else {//其他事件,向后传播,交给其他Handler处理
  10. super.userEventTriggered(ctx, evt);
  11. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/242280
推荐阅读
相关标签
  

闽ICP备14008679号