为什么 protobuf 只读取最后一条消息作为输入结果?
Why protobuf only read the last message as input result?
通常我们使用protobuf来传递一条消息,多次,每次消息内容不同。但是我发现 reader 端似乎处理了整个消息,并且只使用了最后一条消息,如下所示:
$cat 30.proto
message hello
{
required int32 f1=1;
required int32 f2=2;
optional int32 f3=3;
}
$cat 30.cpp
#include "30.pb.h"
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
fstream fo("./log30.data",ios::binary|ios::out);
hello p1,p2,p3;
p1.set_f1(1);
p1.set_f2(2);
p2.set_f1(3);
p2.set_f2(4);
p3.set_f1(5);
p3.set_f2(6);
p1.SerializeToOstream(&fo);
p2.SerializeToOstream(&fo);
p3.SerializeToOstream(&fo);
fo.close();
fstream fi("./log30.data",ios::binary|ios::in);
hello pi;
pi.ParseFromIstream(&fi);
cout<<pi.f1()<<pi.f2()<<endl;
return 0;
}
编译运行,程序输出:
56
好吧,我预计当我第一次从 log30.data 解析时,"pi" 应该读取第一个对象并因此打印“12”。令我惊讶的是,Parse 似乎会转到消息的末尾并给出最后一个消息。
我的问题是,我们使用 pb 作为 rpc encoding/decoding 通道在对等点之间传送许多消息,如果只解析一条消息,它在生产级别的真正用途是什么?可能我的理解有误,还请指正和解释。
非常感谢
您只能将一条消息写入输出流。 API不提供record-separating容器格式!
因此,当您读取数据时,所有内容都被假定为同一消息的一部分,并且遵循仅保留 single-item 字段的最后一个值的通常协议。
通常我们使用protobuf来传递一条消息,多次,每次消息内容不同。但是我发现 reader 端似乎处理了整个消息,并且只使用了最后一条消息,如下所示:
$cat 30.proto
message hello
{
required int32 f1=1;
required int32 f2=2;
optional int32 f3=3;
}
$cat 30.cpp
#include "30.pb.h"
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
fstream fo("./log30.data",ios::binary|ios::out);
hello p1,p2,p3;
p1.set_f1(1);
p1.set_f2(2);
p2.set_f1(3);
p2.set_f2(4);
p3.set_f1(5);
p3.set_f2(6);
p1.SerializeToOstream(&fo);
p2.SerializeToOstream(&fo);
p3.SerializeToOstream(&fo);
fo.close();
fstream fi("./log30.data",ios::binary|ios::in);
hello pi;
pi.ParseFromIstream(&fi);
cout<<pi.f1()<<pi.f2()<<endl;
return 0;
}
编译运行,程序输出: 56
好吧,我预计当我第一次从 log30.data 解析时,"pi" 应该读取第一个对象并因此打印“12”。令我惊讶的是,Parse 似乎会转到消息的末尾并给出最后一个消息。
我的问题是,我们使用 pb 作为 rpc encoding/decoding 通道在对等点之间传送许多消息,如果只解析一条消息,它在生产级别的真正用途是什么?可能我的理解有误,还请指正和解释。
非常感谢
您只能将一条消息写入输出流。 API不提供record-separating容器格式!
因此,当您读取数据时,所有内容都被假定为同一消息的一部分,并且遵循仅保留 single-item 字段的最后一个值的通常协议。