ProtoBuf练习

Posted 银魔术师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

以上是关于ProtoBuf练习的主要内容,如果未能解决你的问题,请参考以下文章

ProtoBuf练习

ProtoBuf练习

ProtoBuf练习

ProtoBuf练习

ProtoBuf练习

spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段