ChannelHandle 在Netty中使用

该代码示例展示了一个自定义的ChannelHandler,继承自SimpleChannelInboundHandler,用于处理ByteBuf类型的数据。类中处理了通道激活、读取数据、异常捕获以及IdleStateEvent事件(写超时和读超时),在超时时可能发送心跳数据或重启连接。这展示了网络通信中防止粘包拆包、连接管理和心跳机制。
摘要由CSDN通过智能技术生成
public class ChannelHandle extends SimpleChannelInboundHandler<ByteBuf> {

    private IChannelHandle iChannelHandle;
    public ChannelHandle(IChannelHandle iChannelHandle){
        this.iChannelHandle = iChannelHandle;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        /**
         * 发送时必须设置标记边界\n或\r\n ,否则会存在粘包拆包的情况
         */
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //处理接收到的数据msg
        Log.d("ccc", "channelRead:---"+msg.toString());
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Log.e("ccc", "channelInactive 连接失败");
        iChannelHandle.restart(true);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Log.i("ccc", "exceptionCaught 连接错误回调");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        Log.d("ccc", "channelRead:--- read1 idle");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state().equals(IdleState.WRITER_IDLE)) {
                //写超时,此时可以发送心跳数据给服务器
                Log.d("ccc", "channelRead write idle");

            }else if (idleStateEvent.state().equals(IdleState.READER_IDLE)){
                //读超时,此时代表没有收到心跳返回可以关闭当前连接进行重连
                Log.d("ccc", "channelRead:--- read2 idle");
                iChannelHandle.restart(true);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值