1. ProtobufVarint32FrameDecoder
该类的类图如下:
image.png
一种解码器,通过消息中的Google Protocol Buffers Base 128 Varents整数长度字段的值来动态分割接收到的ByteBufs。例如:
readRawVarint32方法
从缓冲区读取可变长度的32位int
返回:如果缓冲区readerIndex已被转发,则解码为int,否则为无意义值
2. ProtobufDecoder
image.png3. 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
网友评论