user2626222
user2626222

Reputation: 169

Netty - How to exchange different Protocol Buf objects and decode them?

I am planning on using Protocol Buffers with Netty4.0 for communication between client and server. I have different types of messages (ex: Command Message, Status Message, Health Message etc). Per the API, I need to pass the instance of a message/class to ProtobufDecoder and I can't use more than one decoders to decode a message. How to solve this problem?

Following is some reference code:

        ChannelPipeline p = ch.pipeline();
        p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
        p.addLast("protobufDecoder", new ProtobufDecoder(WorldClockProtocol.LocalTimes.getDefaultInstance()));

        p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
        p.addLast("protobufEncoder", new ProtobufEncoder());

Thanks.

Upvotes: 0

Views: 718

Answers (1)

geri-m
geri-m

Reputation: 705

Inside my protobuf I do have a "cmd" field for the various commands. In my Handler where is a switch-case statement to handel the various cases.

This is how I configure the Initialzier:

ChannelPipeline p = ch.pipeline();
p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
p.addLast("protobufDecoder", new ProtobufDecoder(Proto.Request.getDefaultInstance()));
p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
p.addLast("protobufEncoder", new ProtobufEncoder());
p.addLast("handler", new ClientHandler());

Inside the Handler, in

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{...}

I do have a Switch Case statemt for evaluating the msgTyp I have in the Object (which is a Protobuf in this case)

Upvotes: 1

Related Questions