【问题标题】:Length prefix for protobuf messages in C++C++ 中 protobuf 消息的长度前缀
【发布时间】:2012-07-23 08:40:14
【问题描述】:

我正在使用 protobuf 序列化通过 C++ 中的套接字连接发送的消息。对于通信,我想在消息中添加一个标头,指示消息的长度。你怎么看这个实现?我做了一些研究,这就是我总结的结果。

有没有更好的方法来做到这一点?这个实现会引起任何麻烦吗?我知道有对 Java 的 API 支持,但不幸的是不支持 C++。

bool send_message(int socket, my_protobuf::Message message)
{
  google::protobuf::uint32 message_length = message.ByteSize();
  int prefix_length = sizeof(message_length);
  int buffer_length = prefix_length + message_length;
  google::protobuf::uint8 buffer[buffer_length];

  google::protobuf::io::ArrayOutputStream array_output(buffer, buffer_length);
  google::protobuf::io::CodedOutputStream coded_output(&array_output);

  coded_output.WriteLittleEndian32(message_length);
  message.SerializeToCodedStream(&coded_output);

  int sent_bytes = write(socket, buffer, buffer_length);
  if (sent_bytes != buffer_length) {
    return false;
  }

  return true;
}

bool recv_message(int socket, my_protobuf::Message *message)
{
  google::protobuf::uint32 message_length;
  int prefix_length = sizeof(message_length);
  google::protobuf::uint8 prefix[prefix_length];

  if (prefix_length != read(socket, prefix, prefix_length)) {
    return false;
  }
  google::protobuf::io::CodedInputStream::ReadLittleEndian32FromArray(prefix,
      &message_length);

  google::protobuf::uint8 buffer[message_length];
  if (message_length != read(socket, buffer, message_length)) {
    return false;
  }
  google::protobuf::io::ArrayInputStream array_input(buffer, message_length);
  google::protobuf::io::CodedInputStream coded_input(&array_input);

  if (!message->ParseFromCodedStream(&coded_input)) {
    return false;
  }

  return true;
}

【问题讨论】:

  • 看到这个answer
  • 缓冲区是否必须是 unsigned int8 类型?
  • 你的 socket->write() 如何接受 google::protobuf::uint8 类型的缓冲区?

标签: c++ sockets message protocol-buffers


【解决方案1】:

使用 varint(例如 WriteVarint32)而不是 fixed32(你有 WriteLittleEndian32)更常见,但是通过使用长度前缀来分隔 protobuf 流的做法是合理的。

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2019-11-04
    • 2021-04-21
    • 1970-01-01
    • 2013-04-08
    • 2019-04-12
    • 2018-07-18
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多