netty 中使用 Protobuf

private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) {
            ch.pipeline().addLast("protobufFrameDecoder", new ProtobufVarint32FrameDecoder());

            ch.pipeline().addLast("protobuf decoder", new ProtobufDecoder(SubscribeReqPeoro.SubscribeReq.getDefaultInstance()));

            ch.pipeline().addLast("LengthFieldPrepender", new ProtobufVarint32LengthFieldPrepender());
            ch.pipeline().addLast("protobuf encoder", new ProtobufEncoder());

            ch.pipeline().addLast(new TimeServerHandler());
        }
    }

ChannelPipeline 添加 ProtobufVarint32FrameDecoder, 主要用於半包處理, 後續添加 ProtobufDecoder 解碼器, 它的參數是 com.google.protobuf.MessageLite 實際上就是告訴 ProtobufDecoder 須要解碼的目標類是什麼. 數組

ProtobufVarint32LengthFieldPrepender: 由於 ProtobufEncoder 只是將 message 的各個 filed 按照規則輸出, 並無 serializedSize, 因此 socket 沒法斷定 package(封包). 這個 Encoder 的做用就是在 ProtobufEncoder 生成的字節數組前, 設置 varint32 數字, 表示 serializedSize.socket

相關文章
相關標籤/搜索