java netty之ByteToMessageDecoder

本文详细探讨了Java Netty框架中的ByteToMessageDecoder的实现原理。它继承自ChannelInboundByteHandlerAdapter,核心在于inboundBufferUpdated方法,调用callDecode方法并重写decode方法以将字节数据转换为自定义类型。最终,解码后的数据通过drainToNextInbound方法传递给下一个inbound handler进行处理。
摘要由CSDN通过智能技术生成

在上面的一篇文章中,有说明ByteToMessageDecoder是怎么使用的,那么这一篇就来讲讲它是怎么实现的。。

首先还是来看一下它的继承体系:


它直接继承自ChannelInboundByteHandlerAdapter类型,至于说这个类型的介绍,在前面的文章中就已经有了说明,无非是实现了那些inboundhandler的方法,不过实现的都非常的粗糙,另外一些handler可以直接继承它,重写其中自己感兴趣的方法就可以了。。。

好吧,接下来我们来看看ByteToMessageDecoder的定义吧:

public abstract class ByteToMessageDecoder
    extends ChannelInboundByteHandlerAdapter {

    private volatile boolean singleDecode;
    private boolean decodeWasNull;

    /**
     * If set then only one message is decoded on each {@link #inboundBufferUpdated(ChannelHandlerContext)} call.
     * This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up.
     *
     * Default is {@code false} as this has performance impacts.
     */
    public void setSingleDecode(boolean singleDecode) {
        this.singleDecode = singleDecode;
    }

    /**
     * If {@code true} then only one message is decoded on each
     * {@link #inboundBufferUpdated(ChannelHandlerContext)} call.
     *
     * Default is {@code false} as this has performance impacts.
     */
    public boolean isSingleDecode() {
        return singleDecode;
    }

    @Override
    public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        callDecode(ctx, in);   //当有数据进来的时候,直接调用callDecode方法
    }

    @Override
    public void channelReadSuspended(ChannelHandlerContext ctx) throws Exception {
        if (decodeWasNull) {
            decodeWasNull = false;
            if (!ctx.channel().config().isAutoRead()) {
                ctx.read();
            }
        }
        super.channelReadSuspended(ctx);
    }

    @Override
    public void channelInactive(ChannelH
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值