gpt4 book ai didi

c++ - 在 C++ 中解析 Protocol Buffer

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:38 29 4
gpt4 key购买 nike

我想将一些 Protocol Buffer 写入套接字并从客户端读回。事情不起作用,所以我在编码后立即在服务器本身中编写了一些解码部分。你能看看下面的代码并告诉我我做错了什么吗?

(我不得不使用数组流和编码流,这样我才能写一个分隔符)

int bytes_written = tData.ByteSize() + sizeof(google::protobuf::uint32);
google::protobuf::uint8 buffer[bytes_written];
memset(buffer, '\0', bytes_written);
google::protobuf::io::ArrayOutputStream aos(buffer,bytes_written);
google::protobuf::io::CodedOutputStream *coded_output = new google::protobuf::io::CodedOutputStream(&aos);
google::protobuf::uint32 size_ = tData.ByteSize();
coded_output->WriteVarint32(size_);

tData.SerializeToCodedStream(coded_output);

int sent_bytes = 0;
std::cout << buffer << std::endl;
if ( (sent_bytes = send(liveConnections.at(i), buffer, bytes_written, MSG_NOSIGNAL)) == -1 )
liveConnections.erase(liveConnections.begin() + i);
else
std::cout << "sent " << sent_bytes << " bytes to " << i << std::endl;

delete coded_output;



////////////////


google::protobuf::uint8 __buffer[sizeof(google::protobuf::uint32)];
memset(__buffer, '\0', sizeof(google::protobuf::uint32));
memcpy (__buffer, buffer, sizeof(google::protobuf::uint32));

google::protobuf::uint32 __size = 0;

google::protobuf::io::ArrayInputStream ais(__buffer,sizeof(google::protobuf::uint32));
google::protobuf::io::CodedInputStream coded_input(&ais);
coded_input. ReadVarint32(&__size);
std::cout <<" size of payload is "<<__size << std::endl;

google::protobuf::uint8 databuffer[__size];
memset(databuffer, '\0', __size);
memcpy (databuffer, buffer+sizeof(google::protobuf::uint32), __size);

std::cout << "databuffs " << "size " << __size << " "<< databuffer << std::endl;
google::protobuf::io::ArrayInputStream array_input(databuffer,__size);
google::protobuf::io::CodedInputStream _coded_input(&array_input);
data_model::terminal_data* tData = new data_model::terminal_data();
if (!tData->ParseFromCodedStream(&_coded_input))
{
std::cout << "data could not be parsed" << std::endl;
}
else
{
std::cout <<" SYMBOL --" << tData->symbol_name() << std::endl;
}
delete tData;

程序输出:

size of payload is 55
databuffs size 55 C109"056* BANKNIFTY0���20140915@�J 145406340
data could not be parsed
C109"056* BANKNIFTY0���20140915@�J 145406340

最佳答案

WriteVarint32 不一定写 4 个字节,ReadVarint32 也不一定读 4 个字节。 “var”代表“可变”,如“可变长度编码”。

当编码时,你写下大小(可以少到一个字节),然后是原型(prototype)。解码时,读取大小,然后前进四个字节,然后读取原型(prototype)。所以,您是从错误的偏移量开始解析的。

ReadVarint32 之后使用 CurrentPosition() 计算大小指示器消耗了多少字节。按该字节数前进。

关于c++ - 在 C++ 中解析 Protocol Buffer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25371754/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com