protobuf 确定要反序列化的消息类型

protobuf determining message type to deserialize

使用 protobuf,我们可以定义消息并生成它们的 classes,每个消息都将知道如何 serialize/deserialize 到二进制文件。

假设我们已经定义了多个不同的消息, 我们从网络中获取了一些 byte[],我们如何确定消息类型以使用适当的 class 和反序列化?

你不能。 Protocol buffers 的有线格式不对消息类型进行编码,仅对标记编号和类型进行编码。

例如,以下协议的消息实例的有线格式将是相同的(显然在字符串字段中具有相同的数据):

message Foo {
  optional string foo_field = 1;
}

message Bar {
  optional string field_contained_in_bar = 1;
}

和以下消息的实例 可能 也具有相同的编码,如果仅设置了字符串字段:

message Baz {
  optional string str = 1;
  optional int32 num = 2;
}

您需要知道您希望收到哪种消息类型。

请参考编码示例in the documentation