1. 程式人生 > >ProtoBuf練習(二)

ProtoBuf練習(二)

.proto fstream using 讀寫 get run pro 長度 返回對象

重復數據類型

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

ProtoBuf練習(二)