Netty-心跳检测

IdleStateHandler

IdleStateHandler 是Netty 提供的心跳检测机制。我们先简单的看下这个类的构造函数
IdleStateHandler

  1. readerIdleTime未读到数据的时间
  2. writerIdleTime未写入数据的时间
  3. allIdleTime未读到或者未写入数据的时间
  4. unit对应的时间单位

自定义心跳类

public class IMIdleStateHandler extends IdleStateHandler {

  private static final int READER_IDLE_TIME = 15;

  /**
   * 15s 未收到数据
   */
  public IMIdleStateHandler() {
    super(READER_IDLE_TIME, 0, 0, TimeUnit.SECONDS);
  }

  @Override
  protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
    log.error(READER_IDLE_TIME + "秒未读到数据,关闭连接");
    ctx.channel().disconnect();
  }
}

这里我们自定义的心跳类设置为15s内未收取到数据就关掉链接

然后我们需要在server端假如这个心跳处理类。因为心跳是对收到数据到处理,这里我们建议放在pipeline的第一个。

socketChannel.pipeline().addLast(new IMIdleStateHandler());

分别启动server端和client端之后,我们不做任何操作,15s后会发现在server端的控制台打印如下数据

17:18:00.706 [main] WARN io.netty.bootstrap.ServerBootstrap - Unknown channel option 'SO_KEEPALIVE' for channel '[id: 0x94bea19e]'
17:18:00.722 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x94bea19e] REGISTERED
17:18:00.724 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x94bea19e] BIND: 0.0.0.0/0.0.0.0:8080
17:18:00.725 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x94bea19e, L:/0:0:0:0:0:0:0:0:8080] ACTIVE
17:18:06.854 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x94bea19e, L:/0:0:0:0:0:0:0:0:8080] READ: [id: 0x2337cea3, L:/127.0.0.1:8080 - R:/127.0.0.1:49551]
17:18:06.855 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x94bea19e, L:/0:0:0:0:0:0:0:0:8080] READ COMPLETE
17:18:21.870 [nioEventLoopGroup-3-1] ERROR cn.ddlover.im.business.IMIdleStateHandler - 15秒未读到数据,关闭连接

到这里验证成功。

代码地址(代码我写着玩的,写的不好看到的大佬请见谅):

https://github.com/stormerbo/dd-im
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值