Netty 之 心跳检测

https://www.jianshu.com/p/1a28e48edd92

https://www.jianshu.com/p/0c9112c5ffd1

https://blog.csdn.net/linuu/article/details/51385682

多数文章装逼成分居多。看懂之后就精简为两步:

【顺便吐槽一下:装逼文乍一看好牛逼,看懂之后就莫名讨厌。他妈的简单的东西被你讲的那么复杂,就想着自己懂,还不想让别人轻易搞懂。不想让别人懂就别写出来啊,会点三脚猫功夫就上天了。艹】

第一步: pipeline  加入:IdleStateHandler

ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(5, 0, 0));

第二步:处理类 实现  ChannelInboundHandlerAdapter  接口的函数  userEventTriggered

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                // 在规定时间内没有收到客户端的上行数据, 主动断开连接
                socketChannelMap.remove((SocketChannel)ctx.channel());
                ctx.disconnect();
                System.out.println("心跳检测触发,连接断开!");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
}

猜你喜欢

转载自blog.csdn.net/NRlovestudy/article/details/89787063