Protobuf - 来自同一 class 的多条消息
Protobuf - Multiple messages from the same class
我在 proto
文件中有以下消息
message User
required string name = 1;
required string password = 2;
- 如何区分同一消息的多个实例?
- 如果我想序列化一个应用程序的注册用户,例如
- 是否为此指定了 protobuf?
这只适用于一些额外的编码。当 protobuf 从流中读取一条消息时,它不知道一条消息的长度。它仅将字段流视为 name/value 对,没有消息开始或结束的指示符。
来自docs:
If you want to write multiple messages to a single file or stream, it is up to you to keep track of where one message ends and the next begins. The Protocol Buffer wire format is not self-delimiting, so protocol buffer parsers cannot determine where a message ends on their own.
Google 的实现包含此用例的一些帮助程序 类。看看 CodedInputStream and CodedOutputStream.
一种可能的写法:
- 序列化一个对象到内存缓冲区
- 使用 CodedOutputStream 将缓冲区的长度作为单个数字写入输出流
- 将包含序列化对象的内存缓冲区添加到输出流
- 继续下一个对象
一种可能的阅读方式:
- 使用 CodedInputStream 从输入流中读取一个数字
- 从输入流中取出这个数字指示内存缓冲区的字节数
- 解析此缓冲区以重新获得 一个 对象
- 如果输入流有更多字节,则继续下一个对象
我在 proto
文件中有以下消息
message User
required string name = 1;
required string password = 2;
- 如何区分同一消息的多个实例?
- 如果我想序列化一个应用程序的注册用户,例如
- 是否为此指定了 protobuf?
这只适用于一些额外的编码。当 protobuf 从流中读取一条消息时,它不知道一条消息的长度。它仅将字段流视为 name/value 对,没有消息开始或结束的指示符。
来自docs:
If you want to write multiple messages to a single file or stream, it is up to you to keep track of where one message ends and the next begins. The Protocol Buffer wire format is not self-delimiting, so protocol buffer parsers cannot determine where a message ends on their own.
Google 的实现包含此用例的一些帮助程序 类。看看 CodedInputStream and CodedOutputStream.
一种可能的写法:
- 序列化一个对象到内存缓冲区
- 使用 CodedOutputStream 将缓冲区的长度作为单个数字写入输出流
- 将包含序列化对象的内存缓冲区添加到输出流
- 继续下一个对象
一种可能的阅读方式:
- 使用 CodedInputStream 从输入流中读取一个数字
- 从输入流中取出这个数字指示内存缓冲区的字节数
- 解析此缓冲区以重新获得 一个 对象
- 如果输入流有更多字节,则继续下一个对象