• 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;
    }
    
  • 相关阅读:
    linux下最大文件数
    Apache实现Web Server负载均衡
    linux环境变量
    iptables用法
    read 不回显的方法
    Linux间的进程通信;以及子进程的创建
    Linux总结
    自实现部分string类的功能
    C语言 (内存) 四道经典题目
    STL 容器(vector 和 list )
  • 原文地址:https://www.cnblogs.com/silvermagic/p/9087610.html
Copyright © 2020-2023  润新知