Consider the following implementation:
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;
}
Using: https://developers.google.com/protocol-buffers/ In a real world situation the receiver will not know the amount of bytes that should be received, but protobuf should (to my understanding) be able to check for a complete message from the buffer. This seems to work fine if there are no optional messages. At this moment it does not happen and I end up with a broken person with no phone number. :) What am I doing wrong and how should this situation be handled?