Google之Protocol Buffer序列化学习(一)

本文介绍了Google的Protocol Buffer在Linux上的安装过程,以及如何使用它来定义消息结构、生成接口文件,并通过一个简单的聊天室应用展示了消息的序列化和反序列化。文中给出了服务器端和客户端的代码示例,展示了Protocol Buffer在实际项目中的基本应用。
摘要由CSDN通过智能技术生成

很早就听闻过Protocol Buffer是个很神奇的东西,只是没有使用过,由于工作上的需要,决定试试Protocol Buffer,废话不多说,先来看看如何安装Protocol Buffer吧,平台是Linux

安装步骤:

1)下载Protocol Buffer源码包 https://code.google.com/p/protobuf/downloads/list

2)   使用  tar -xvf protobuf-2.5.0.tar.bz2

3)   开始编译protocol buffer 

    1. ./configure --prefix=/usr/local/protobuf

     2. make

    3. make check

    4. make install

经过了这些步骤之后,就可以开始我们的Protocol Buffer之旅了,下面我们就从最简单的开始吧,一探究竟,在写Protocol Buffer应用之前,我们需要知道使用Protocol Buffer的使用步骤:

     1)定义消息结构文件,一般都是以.proto为后缀

      2)使用Protocol Buffer 编译器来编译消息结构文件,并且生成对应的***.pb.h 和***.pb.cc文件

      3)使用生成的接口文件中的API来实现消息发送与接收

看完了上述步骤之后,我们来写个简单的测试例子,代码如下:

1. 首先定义消息的结构

message Person{
    required string name = 1;
    required int32 id = 2;
    optional string email = 3;
}

message AddressBook{
    repeated Person person = 1;
}

在这个结构中,我们定义了两个子结构,其中AddressBook结构包含了一个Person结构,下面我们就使用protoc -I=. --cpp_out=. ./test.proto 来生成test.pb.h和test.pb.cc文件,其中文件test.pb.h文件中生成了很多的接口API,其中我们只需要使用其中的部分API来完成,接下来,我们来看看怎么来使用这些API吧,代码如下:

#include <iostream>
#include <fstream>
#include <string>
#include "test.pb.h"
using namespace std;

void People(const Person& person)
{
    cout << "Person ID: " << person.id() << endl;
    cout << "Name: " << person.name() << endl;
    if (person.has_email()) {
        cout << "E-mail address: " << person.email() << endl;
    }
}

// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const AddressBook& address_book) {
    for (int i = 0; i < address_book.person_size(); i++) {
        const Person& person = address_book.person(i);
        People(person);
    }
}

void write(const char* filename)
{
    Person person;
    person.set_id(123);
    person.set_name("abc");
    person.set_email("abc@126.com");

    fstream out(filename,ios::out |ios::binary | ios::trunc);
    person.SerializeToOstream(&out);
    out.close();
}
// Main function:  Reads the entire address book from a file and prints all
//   the information inside.
int main(int argc, char* argv[]) {
    // Verify that the version of the library that we linked against is
    // compatible with the version of the headers we compiled against.
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    if (argc != 2) {
        cerr << "Usage:  " << argv[0] <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值