netty实现心跳连接

用这个例子举例

在上述例子的事件处理流上加上心跳连接

  @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //对ByteBuf数据流进行处理,转换成http的对象
                        pipeline.addLast(new HttpServerCodec());// Http消息编码解码
                        pipeline.addLast(new HttpObjectAggregator(64*1024));
                        pipeline.addLast(new IdleStateHandler(5, 0, 0)); //心跳
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new SocketHandler());//自定义处理类
                    }

再在自定义的事件处理器上,重写心跳断开后的处理事件

      //关闭连接
    @Override  
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {  
        if (evt instanceof IdleStateEvent) {  
            IdleStateEvent event = (IdleStateEvent) evt;  
            if (event.state() == IdleState.READER_IDLE) {  
                    ctx.channel().close();  
                    System.out.println("连接超时,将关闭链路");
            }  
        } else {  
            super.userEventTriggered(ctx, evt);  
        }  
    } 

效果
1连接上socket服务器
这里写图片描述

2在5秒之内可以正常通讯
这里写图片描述
3 5秒后触发断开方法断开链路,通讯中断

这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39168678/article/details/80604338