我正在尝试通过 HTTP 连接发送一个 Google Protocol Buffer 序列化字符串并将其接收回来(未修改),我将在其中反序列化它。我的问题似乎与 'serializeToString' 方法有关,该方法采用我的字符串并似乎将换行符(可能还有其他空格)添加到序列化字符串中。在下面的示例中,我使用字符串“camera_stuff”,在对其进行序列化后,我得到一个 QString,前面有换行符。我尝试了其他具有相同结果的字符串,只是添加了不同的空格和换行符。这会导致我的反序列化操作出现问题,因为 HTTP 请求中未捕获空格,因此无法成功解码来自服务器的包含序列化字符串的响应。如果我猜到序列化字符串中的空格,我可以部分解码它。我该如何解决这个问题?请参阅以下代码 - 谢谢。
我有一个协议缓冲区 .proto 文件,如下所示:
message myInfo {
required string data = 1;
required int32 number = 2;
}
运行 protoc 编译器后,我在其中构造 Qt,如下所示:
// Now Construct our Protocol Buffer Data to Send
myInfo testData;
testData.set_data("camera_stuff");
testData.set_number(123456789);
我将我的数据序列化为这样的字符串:
// Serialize the protocol buffer to a string
std::string serializedProtocolData; // Create a standard string to serialize the protocol buffer contents to
myInfo.SerializeToString(&serializedProtocolData); // Serialize the contents to the string
QString serializedProtocolDataAsQString = QString::fromStdString(serializedProtocolData);
然后我像这样打印出来:
// Print what we are sending
qDebug() << "Sending Serialized String: " << serializedProtocolDataAsQString;
qDebug() << "Sending Serialized String (ASCII): " << serializedProtocolDataAsQString.toAscii();
qDebug() << "Sending Serialized String (UTF8): " << serializedProtocolDataAsQString.toUtf8();
qDebug() << "Sending Serialized Protocol Buffer";
qDebug() << "Data Number: " << QString::fromStdString(myInfo.data());
qDebug() << "Number: " << (int)myInfo.number();
当我将数据作为 HTTP 多部分消息的一部分发送时,我会看到这样的打印语句(注意打印输出中的换行符!):
Composing multipart message...
Sending Serialized String: "
camera_stuffï:"
Sending Serialized String (ASCII): "
camera_stuffï:"
Sending Serialized String (UTF8): "
camera_stuffÂÂï:"
Sending Serialized Protocol Buffer
Data: "camera_stuff"
Number: 123456789
Length of Protocol Buffer serialized message: 22
Loading complete...
客户端反序列化消息如下:
// Now deserialize the protocol buffer
string = "\n\n" + string; // Notice that if I don't add the newlines I get nothing!
myInfo protocolBuffer;
protocolBuffer.ParseFromString(string.toStdString().c_str());
std::cout << "DATA: " << protocolBuffer.model() << std::endl;
std::cout << "NUMBER: " << protocolBuffer.serial() << std::endl;
qDebug() << "Received Serialized String: " << string;
qDebug() << "Received Deserialized Protocol Buffer";
qDebug() << "Data: " << QString::fromStdString(protocolBuffer.data());
qDebug() << "Number: " << (int)protocolBuffer.number();
服务器返回它而不对序列化的字符串做任何事情,客户端打印以下内容:
RESPONSE: "camera_stuffï:"
DATA: camera_stu
NUMBER: 0
Received Serialized String: "
camera_stuffï:"
Received Deserialized Protocol Buffer
Number: "camera_stu"
Number: 0
所以你看到的问题是我无法猜测空格,所以我似乎无法可靠地反序列化我的字符串。有什么想法吗?