ProtoBuf练习(二)

重复数据类型

protobuf语言的重复字段类型相当于C++的std::list数据类型

工程目录结构

$ ls proto/
TServer.proto  TSession.proto

proto文件

$ cat TSession.proto
syntax = "proto3";

//枚举类型可以放外面,也可以放message里面
enum Status
{
    INVALID = 0;
    VALID = 1;
};

message TSession
{
    string owner = 1;
    Status status = 2;
};

$ cat TServer.proto
syntax = "proto3";

import "TSession.proto";

//通过repeated来模拟链表的可变长度
message TServer
{
    repeated TSession sessions = 1;
};

读写源文件

$ cat writer.cpp
#include <fstream>
#include <iostream>
#include <string>
#include "TServer.pb.h"

using namespace std;

int main(int argc, char *argv[])
{
    TServer srv;
    std::string owner;
    while(true)
    {
        std::getline(std::cin, owner);
        if (owner.empty())
            break;
        //自动生成一个新的节点,并返回对象指针
        TSession* s = srv.add_sessions();
        s->set_owner(owner);
        s->set_status(Status::VALID);
    }

    fstream output("./log", ios::out | ios::trunc | ios::binary);
    cout << "Serialize start." << endl;
    if (!srv.SerializeToOstream(&output))
        {
                cout << "Serialize failed." << endl;
                return -1;
        }
    output.close();
    cout << "Serialize end." << endl;
    return 0;
}

$ cat reader.cpp
#include <fstream>
#include <iostream>
#include "TServer.pb.h"

using namespace std;

int main(int argc, char *argv[])
{
    fstream input("./log", ios::in | ios::binary);
    cout << "Deserialize start." << endl;

    TServer srv;
    if (!srv.ParseFromIstream(&input))
    {
        cout << "Deserialize failed." << endl;
        return -1;
    }
    cout << "First Method" << endl;
    for (int i = 0; i < srv.sessions_size(); i++)
        srv.sessions(i).PrintDebugString();

    cout << "Second Method" << endl;
    auto sessions = srv.sessions();
    for (auto iter = sessions.begin(); iter != sessions.end(); iter++)
        iter->PrintDebugString();

    cout << "Deserialize end." << endl;
    input.close();
    return 0;
}
原文地址:https://www.cnblogs.com/silvermagic/p/9087610.html