1

考虑以下实现:

人.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;
}

主.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 应该(据我了解)能够检查完整的来自缓冲区的消息。如果没有可选消息,这似乎工作正常。此刻它没有发生,我最终得到了一个没有电话号码的破碎的人。:) 我做错了什么,这种情况应该如何处理?

4

1 回答 1

0

Protocol Buffers 序列化格式不包括框架(即将序列化消息打包到流或分隔消息)。你需要自己做。

但是,有一些既定的做法。检查这两个答案以获取详细信息:

于 2012-06-03T18:41:17.990 回答