Protocol-Buffers – Best Practice for Determining Protocol Buffer Message Types

I need to serialize and deserialize a series of protocol buffer messages in the byte stream. There are some predetermined message types. What is the recommended way to encode type information so that Can my application know which type it should read?
The most common method is to use union message.

For example:

message AnyMessage {
optional Message1 msg1 = 1;
optional Message2 msg2 = 2;
...
}

Then encode/decode all messages within the AnyMessage container. Starting from protobuf 2.6, you can also use the oneof specifier, which will ensure that only one sub-message is set.

The most common method is to use union message.

For example:

message AnyMessage {
optional Message1 msg1 = 1;
optional Message2 msg2 = 2;
...
}

Then encode/decode everything in the AnyMessage container Message. Starting from protobuf 2.6, you can also use the oneof specifier, which will ensure that only one sub-message is set.

Leave a Comment

Your email address will not be published.