FixedLengthFrameDecoder

固定长度解码器

  • 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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容