考虑以下实施:
person.proto:
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required float number = 1;
required PhoneType type = 2;
}
message Person {
required string name = 1;
optional PhoneNumber number = 2;
}
main.cpp中:
#include <stdint.h>
#include <stdio.h>
#include "person.pb.h"
#include <iostream>
int main(int argc, char *argv[])
{
static const uint32_t outputbuflen = 1024;
uint8_t outputbuffer[outputbuflen];
uint32_t writtenlenght = 0;
// Encode a person and send it over any datalink.
// SENDER
Person p_sender;
p_sender.set_name("FooBar");
// Set the phonenumber.
// Does not work because returns const ref.
// p.number().set_number(0123123);
// Is this correct?
PhoneNumber * number = p_sender.mutable_number();
number->set_number(0800123123.0);
number->set_type(MOBILE);
p_sender.SerializeToArray(outputbuffer, outputbuflen);
writtenlenght = p_sender.ByteSize();
std::cout << writtenlenght << "B written to output."<< std::endl;
// Great, now send the stream somwhere
// sendStream(...);
// RECEIVER
// Does not know how many bytes to expect, so we'll let protobuf handle that.
// Simulate a reception loop.
Person p_receiver;
uint32_t bytesparsed;
for(bytesparsed = 0; bytesparsed < writtenlenght; bytesparsed++){
// Look at the data as if receiving it byte by byte.
std::cout << "Trying to parse message " << bytesparsed << std::endl;
if(p_receiver.ParseFromArray(outputbuffer, bytesparsed)){
std::cout << "Found message" << std::endl;;
break;
}
}
std::cout << "Needed " << bytesparsed << "B to read message, but has still " \
<< writtenlenght - bytesparsed << "B left in buffer" << std::endl;
return 0;
}
使用:https://developers.google.com/protocol-buffers/ 在现实世界的情况下,接收器将不知道应该接收的字节数量,但是protobuf应该(根据我的理解)能够检查来自缓冲器的完整消息。如果没有可选消息,这似乎工作正常。在这一刻它没有发生,我最终得到一个没有电话号码的破碎的人。 :)我做错了什么,应该如何处理这种情况?
答案 0 :(得分:0)
协议缓冲区序列化格式不包括成帧(即将序列化消息打包到流或分隔消息)。你需要自己做。
但是,有一些既定的做法。请查看这两个答案以获取详细信息: