netty4 如何建立心跳机制

服务端增加对空闲时间处理pipeline.addLast("ping", new IdleStateHandler(60, 15, 13,TimeUnit.SECONDS)) 然后在业务逻辑的Handler里面,重写 userEventTriggered(ChannelHandlerContext ctx, Object evt),如果获取到IdleState.ALL_IDLE则定时向客户端发送心跳包;客户端在业务逻辑的Handler里面,如果接到心跳包,则向服务器发送一个心跳反馈;服务端如果长时间没有接受到客户端的信息,即IdleState.READER_IDLE被触发,则关闭当前的channel。

我这样写,把心跳机制和业务逻辑放在了同一个Handler里面处理。而我在http://blog.csdn.net/qian_348840260/article/details/8990657 这里看到的说法是:我们也必须提供专门的心跳处理的Handler,遇到心跳消息,不会继续传递给后面的Handler进行处理,以不影响正常业务。正常的业务请求都不做处理直接传递给后面的Handler。  但是这篇博文介绍的是netty3的实现,在netty4里面,IdleStateAwareChannelHandler 类被取消了,我尝试找netty4的心跳实例,但找了一天都找不到。因此想向你请教一下,在netty4里面应该如何实现心跳机制?能否提供一份实例?

感激万分! 

补充一下,这是我现在的代码,业务逻辑和心跳机制混在一起了,感觉效率会很低下,所以想请教一下怎么改:

服务端:
ServerInitializer

?

public class ServerInitializer extends ChannelInitializer<SocketChannel> {
 
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
 
        pipeline.addLast("ping", new IdleStateHandler(60, 15, 13,
                TimeUnit.SECONDS));
        // 以("\n")为结尾分割的 解码器
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192,
                Delimiters.lineDelimiter()));
        // 字符串解码 和 编码
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        // 自己的逻辑Handler
        pipeline.addLast("handler", new ServerHandler());
    }
}

ServerHandler

public class ServerHandler extends SimpleChannelInboundHandler<String> {
 
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg)
            throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);
        if (!"OK".equals(msg)) {
            //业务逻辑
        }
    }
 
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                System.out.println("READER_IDLE");
                // 超时关闭channel
                ctx.close();
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                System.out.println("WRITER_IDLE");
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                System.out.println("ALL_IDLE");
                // 发送心跳
                ctx.channel().write("ping\n");
            }
        }
        super.userEventTriggered(ctx, evt); 
    }
}

?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值