Protocol Buffers (Google 专用的通讯协议)

转自:http://www.cellopoint.com/cn/media_resources/blogs/2011/05/Protocol_Buffers

Introduction 简介
Protocol buffers 是一个灵活的,高效的,有自动机制(可能指编解碼)工具用于序列化结构数据。
类似 XML,但是更小、更快、更简单。你定义你的结构化数据,然后就可以使用工具生成的特殊代码方便的使用各种语言 (c++ python java)
从各种数据流中读写你的结构化数据。你甚至可在不打断已经部署的程序的情况下重新更新你的数据结构(热部署)。

Why not just use XML? 为什么不使用XML?
protocol buffer 有很多 XML 不具备的优点:
1.简单;
2.小巧:3-10倍
3.效率高:20-100倍
4.无双重义意
5.有自动工具生成

How do they work? 如何开始运作?
你只需要安装 google 的 protocol buffer
编辑 .proto 檔
执行 protoc –cpp_out=. 檔名


Example: 范例 1
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;

enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
message AddressBook {
repeated Person person = 1;
}

Three type 三种数据型态
required:必须提供字段值,否则对应的 message 就会被认为是“未初始化的。“
optional:字段值指定与否都可以。如果没有指定一个可选的字段值,它就会使用默认值。
repeated:字段会重复 n 次(可以为 0)。重复的值的顺序将被保存在缓冲区中的协议。

Required 是永久性的:在把一个字段标识为 Required 的时候,你应该特别小心。

Start working 开始

  • protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto

这会产生以下文件
addressbook.pb.h:声明你生成的 class 的标头檔。
addressbook.pb.cc:你生成的 class 的实作档。

Example: 范例 2
Person person;
person.set_name("John Doe");
person.set_id(1234);
person.set_email("jdoe@example.com");
fstream output("myfile", ios::out | ios::binary);
person.SerializeToOstream(&output);

fstream input("myfile", ios::in | ios::binary);
Person person;
person.ParseFromIstream(&input);
cout << "Name: " << person.name() << endl;
cout << "E-mail: " << person.email() << endl;

Entire message, including: 内部 API
bool IsInitialized() const;:检查是否全部的 required 字段都被设置(set)了值。
string DebugString() const;:返回一个可读的讯息表示形式,对读取特别有用。
void CopyFrom(const Person& from);:用外部讯息的值,覆写调用者讯息内部的值。
void Clear();:将所有项回复到空状态(empty state)。
bool SerializeToString(string* output) const;:将消息序列化并储存在指定的字符串中。注意里面的内容是binary 的;我们只是使用字符串作为一个很方便的容器。
bool ParseFromString(const string& data);:从给定的 string 解析讯息。
bool SerializeToOstream(ostream* output) const;:将讯息写入到给定的 C++ ostream 中。
bool ParseFromIstream(istream* input);:从给定的 C++ istream 解析讯息。

http://code.google.com/intl/zh-TW/apis/protocolbuffers/docs/overview.html
http://www.cppprog.com/2010/0908/207_4.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值