使用C API在协议缓冲区中解析误差

Parsing error in Protocol Buffer using C++ API

本文关键字:误差 缓冲区 协议 API 使用      更新时间:2023-10-16

我有一个test.proto文件,其中所示的代码。我正在我的客户端服务器程序中使用此文件生成的代码。

message Person {
required string user_name        = 1;
optional int32  favourite_number = 2;
repeated string interests        = 3;

}

客户端我没有问题发送数据,但是在服务器端,我正在获得协议缓冲区解析错误(在文件中: protobuf message_lite.cc(line123))说" cant of type'cant它缺少所需字段:user_name"

尽管我已经检查了我的客户端,但找不到任何错误,但是我可能会在服务器端缺少一些没有读取字符串数据的东西?

               //Server side code for Protocol Buffers
               Person filldata;
       google::protobuf::uint32 size;
               //here i might need google::protobuf::string stsize; Not sure ?
       google::protobuf::io::ArrayInputStream ais(buffer,filldata.ByteSize());
       CodedInputStream coded_input(&ais);
       coded_input.ReadVarint32(&size);
               //have tried here both coded_input.ReadString and coded_input.ReadRaw
       filldata.ParseFromCodedStream(&coded_input);
       cout<<"Message is "<<filldata.DebugString();
               //still getting same error have no idea what to do exactly to fix it :(

在这里看了看,但仍然无法从该解释中得到它,希望有人可以修复它。

谢谢!

google::protobuf::io::ArrayInputStream ais(buffer,filldata.ByteSize());

此时,filldata是一条新的消息,因此filldata.ByteSize()为零。因此,您正在告诉Protobufs解析一个空数组。因此,没有设置字段,您会收到所需的字段错误。消息的长度可变,因此您需要确保从服务器传递确切的消息大小。