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