美文网首页
FixedLengthFrameDecoder

FixedLengthFrameDecoder

作者: Pillar_Zhong | 来源:发表于2019-08-01 21:29 被阅读0次

固定长度解码器

  • For example, if you received the following four fragmented packets:

  • <pre>

  • +---+----+------+----+

  • | A | BC | DEFG | HI |

  • +---+----+------+----+

  • </pre>

  • A FixedLengthFrameDecoderwill decode them into the following three packets with the fixed length:

  • <pre>

  • +-----+-----+-----+

  • | ABC | DEF | GHI |

  • +-----+-----+-----+

解码

protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // 解码
    Object decoded = decode(ctx, in);
    // 如果解码成功,那么将返回结果添加到out中
    if (decoded != null) {
        out.add(decoded);
    }
}
protected Object decode(
        @SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    // 如果没有到达规定的定长,那么返回null
    // 在ByteToMessageDecode那边会认为没有读取任何数据,直接结束循环,等待下次读取事件的到来
    if (in.readableBytes() < frameLength) {
        return null;
    } else {
        // 可见数据满足要求, 截取定长的数据返回.
        return in.readRetainedSlice(frameLength);
    }
}

readRetainedSlice

// 这里实际上是生成源Buffer的只读缓冲区,且retain
public ByteBuf readRetainedSlice(int length) {
    ByteBuf slice = retainedSlice(readerIndex, length);
    readerIndex += length;
    return slice;
}

相关文章

网友评论

      本文标题:FixedLengthFrameDecoder

      本文链接:https://www.haomeiwen.com/subject/qtlhdctx.html