简体   繁体   English

Protobuf-来自同一类别的多个消息

[英]Protobuf - Multiple messages from the same class

I have the following message in a proto file 我在proto文件中有以下消息

message User
required string name = 1;
required string password = 2;
  • How can I differentiate multiple instances of the same message? 如何区分同一封邮件的多个实例?
  • If I wanted to serialize the registered users of an app for instance 例如,如果我想序列化应用程序的注册用户
  • Is protobuf indicated for that? 是否指定了protobuf?

This only works with some additional coding. 这仅适用于一些其他编码。 When protobuf reads a message from a stream it does not know the length of one message. 当protobuf从流中读取一条消息时,它不知道一条消息的长度。 It sees simply a stream of fields as name/value pairs and no indicator for start or end of a message. 它仅将字段流视为名称/值对,而没有指示消息开始或结束的指示符。

From the 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's implementations contains some helper classes for this usecase. Google的实现包含此用例的一些帮助程序类。 Have a look at CodedInputStream and CodedOutputStream . 看一下CodedInputStreamCodedOutputStream

One possible way for writing: 一种可能的书写方式:

  • serialize one object to a memory buffer 一个对象序列化到内存缓冲区
  • use CodedOutputStream to write the length of the buffer as a single number to the output stream 使用CodedOutputStream将缓冲区的长度作为一个数字写入输出流
  • add the memory buffer containing your serialized object to the output stream 将包含序列化对象的内存缓冲区添加到输出流
  • proceed with the next object 继续下一个对象

One possible way for reading: 一种可能的阅读方式:

  • use CodedInputStream to read one number from the input stream 使用CodedInputStream从输入流中读取一个数字
  • take as many bytes from the input stream as this number indicates to a memory buffer 从输入流中提取尽可能多的字节(此数字指示该字节指向内存缓冲区)
  • parse this buffer to regain one object 解析此缓冲区以重新获得一个对象
  • if the input stream has more bytes continue with the next object 如果输入流有更多字节,则继续下一个对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM