protobuf:如何在CodedOutputStream中使用GZipOutputStream?

时间:2012-11-24 21:26:19

标签: c++ sockets protocol-buffers

通过套接字传输数据我使用下面的'sendData'方法。由于数据量可以变得非常大(~250000 - 500000字节),我想使用GZipOutputStream来压缩protobuf消息。我面临的问题是,我无法获得压缩消息的大小来预先添加它。

我如何将GZipOutputStream与CodedOutputStream结合使用?

void CommIF::sendData(FVMsg message, vector<int> clients)
{   
  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);

  for (vector<int>::iterator it = clients.begin(); it!=clients.end(); ++it) {
    int client = *it;
    int sent_bytes = write(client, buffer, buffer_length);
    if (sent_bytes != buffer_length) {
      ERROR_LOG("problems sending . Only sent " << sent_bytes << " bytes");
    }
    else
    {
      DBG_LOG("Successfully sent " << sent_bytes << " bytes");
    }
  }
}

0 个答案:

没有答案