netty之编解码proto

1. ProtobufVarint32FrameDecoder

该类的类图如下:


image.png

一种解码器,通过消息中的Google Protocol Buffers Base 128 Varents整数长度字段的值来动态分割接收到的ByteBufs。例如:

image.png

readRawVarint32方法
从缓冲区读取可变长度的32位int
返回:如果缓冲区readerIndex已被转发,则解码为int,否则为无意义值

2. ProtobufDecoder

image.png

3. ProtobufVarint32LengthFieldPrepender

该类类图如下:


image.png

一个编码器,用于预处理Google Protocol Buffers Base 128 Varents整数长度字段。例如:


image.png

4. ProtobufEncoder

该类的类图如下:


image.png

将请求的Google Protocol Buffers Message和MessageLite编码为ByteBuf。TCP/IP的典型设置是:

 ChannelPipeline pipeline = ...;
 
  // Decoders
  pipeline.addLast("frameDecoder",
                   new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
  pipeline.addLast("protobufDecoder",
                   new ProtobufDecoder(MyMessage.getDefaultInstance()));
 
  // Encoder
  pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
  pipeline.addLast("protobufEncoder", new ProtobufEncoder());

然后您可以使用MyMessage而不是ByteBuf作为消息:

 void channelRead(ChannelHandlerContext ctx, Object msg) {
      MyMessage req = (MyMessage) msg;
      MyMessage res = MyMessage.newBuilder().setText(
                                "Did you say '" + req.getText() + "'?").build();
      ch.write(res);
  }

参考:https://blog.csdn.net/xiao_gu_yu/article/details/124757349

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

推荐阅读更多精彩内容