Why protobuf only read the last message as input result?

浪尽此生 提交于 2021-01-27 17:45:39

问题


Usually, we use protobuf to communicate a message, for multiple times, each with different message content. But I found seems the reader side process the whole message, and only the last one is used, like below:

$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;
}

Compile and run, the program outputs: 56

Well, I expected that when I first parse from log30.data, the "pi" should read the first object and thus print "12". To my supprise, seems the Parse will go to the end of the message and give the final one.

My question is, we use pb as a rpc encoding/decoding channel to convey many messages between peers, if only one message is being parsed, what's its really usage in production level? Maybe my interpretation is incorrect, please kindly correct and explain.

Thanks a lot


回答1:


You must only write one message to the output stream. The API does not provide a record-separating container format!

Thus when you read the data everything is assumed to be part of the same message, and the usual protocol of retaining only the last value for single-item fields is followed.



来源:https://stackoverflow.com/questions/41626128/why-protobuf-only-read-the-last-message-as-input-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!