ByteToMessageDecoder注意readerIndex

Netty的ByteToMessageDecoder是一个比较特殊的ChannelHandler,他在整个pipeline中只能有一个,而且只能放在第一位。需要实现decode方法。

public class TestDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
    }

    private Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        int readableBytes = in.readableBytes();
        if (readableBytes < 4) {
            return null;
        }

//      read会改变readerIndex,所以read之前做标记,如果不能读成功,将readerIndex还原
//        in.markReaderIndex(); 
//        int size = in.readInt();

//      或者采用get的方式读,这样readerIndex不会移动
        int size = in.getInt(0);
        if (size <= 0) {
//            in.resetReaderIndex();
            return null;
        }

        if (size > in.readableBytes()) {
//            in.resetReaderIndex();
            return null;
        }

        byte[] bytes = new byte[size];
//      get方式readerIndex还是在初始位置,所以要跳过size的四个字节
        in.skipBytes(4);
        in.readBytes(bytes);
        String json = new String(bytes, StandardCharsets.UTF_8);
        log.info("TestDecoder decode json:{}", json);
        return json;
    }
}

in是原始的输入流,通常这是一个DirectByteBuf,如果docode的时候发现所需数据不足,则必须要直接返回,不能往out里加null对象,add方法会检测decoded对象不能为空;同时,为了让下一次有数据来到且数据充足的时候能完整地读到整个数据,必须将in的readerIndex重置到原始位置。

除非特殊需求要丢掉一些bytes,否则应该严格遵循一个原则:in读了多数bytes(readerIndex移动了多少),那么对应的out应该要输出多少对应的数据。

ByteToArrayDecoder在整个pipeline链路中只能有一个,它是处理原始字节流ByteBuf的,所以它一般是放在链路的第一位;即使你的一个ByteToMessageDecoder的输出任然是一个ByteBuf对象,你的pipeline的下一个channelHandler也不能是ByteToMessageDecoder,而必须要用MessageToMessageDecoder<ByteBuf>。这个可以参考内置的两个InboundChannelHandler

   // Decoders
   pipeline.addLast("frameDecoder",
                    new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
   pipeline.addLast("bytesDecoder",
                    new ByteArrayDecoder());

附带官网关于ByteToMessageDecoder的说明:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值