解析c++中的协议缓冲区
Parsing protocol buffers in c++
我想写一些协议缓冲区到套接字,并从客户端读取它。事情没有工作,所以我写了一些解码部分在服务器本身后,我编码它。你能看看下面的代码,告诉我我做错了什么吗?
(我必须使用arraystream和coded stream,这样我才能写一个分隔符)
int bytes_written = tData.ByteSize() + sizeof(google::protobuf::uint32);
google::protobuf::uint8 buffer[bytes_written];
memset(buffer, ' ', 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, ' ', 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, ' ', __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"代表"可变",如"可变长度编码"。
编码时,先写入大小(可以少到一个字节),然后立即写入原型。解码时,读取大小,然后向前推进四个字节,然后读取原型。因此,您从错误的偏移量开始解析。
在ReadVarint32
之后使用CurrentPosition()
来计算大小指示器消耗了多少字节。
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何使用ZeroMQ为协议缓冲区编写自己的RPC实现
- 协议缓冲区字符串字段的文本编码
- 构建使用协议缓冲区(不含 APK)的 Android 可执行 gRPC 服务器
- 无法使用 ReadBinaryProto Tensorflow 加载协议缓冲区
- 协议缓冲区的静态链接会导致与现有符号冲突
- 协议缓冲区ParseFromString不检查消息结尾
- 与Qt交叉编译到Raspberry Pi 3B+通讯录(协议缓冲区)-错误符号查找错误
- 编译的谷歌协议缓冲区不工作(C++)
- 使用协议缓冲区创建通用反序列化程序
- 在协议缓冲区 c++ 中反序列化字符串数组
- 如何释放协议缓冲区内存
- 协议缓冲区错误版本
- 协议缓冲区#3将消息从c ++发送到c#
- 该程序是针对协议缓冲区运行时库的2.6.1版本编译的,该版本与已安装的版本(3.5.0)不兼容
- 浅拷贝到协议缓冲区的字节字段中
- 协议缓冲区2和3在同一C Linux应用程序中
- 使用谷歌协议缓冲区 - 如何在.proto文件中定义字段
- 我是否需要删除传递给谷歌协议缓冲区(protobuf)的对象