Protocol Buffer基础

目录

概述

How do protocol buffer work?

定义Protocol Format

编译protocol buffers

Propocol Buffers API

Standard Message Methods

Parsing and Serialization

Writing A Message

Reading A Message

Extending A Protocol Buffer


概述

官网的说明:

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.

protocol buffers是Google开发的一套机制,跟开发语言和平台无关,且支持扩展,用于序列化结构化数据。类似于XML,但比XML更轻,更快,更简单。开发者可以定义数据如何被结构化,然后用特定产生的源码生成和读取结构化数据。

为什么不用XML

  • 更简单
  • 用XML进行序列化的数据,比用protocol buffers大3-10倍。
  • protocol buffers的解析速度是XML的20-100倍
  • 更清晰
  • 提供数据访问类,方便开发

How do protocol buffer work?

通过在.proto文件中定义protocol buffer message types,开发者可以指定如何序列化数据。每个protocol buffers message都是一个小的logical record of information,其中包含一系列name-value键值对。

定义Protocol Format

Python tutorial使用了一个例子,是地址簿(address book)。在地址簿的每个人都有一个名字,一个ID,一个email地址和一个联系电话号码。本例中,我们定义addressbook.proto。

syntax = "proto2";

package tutorial;                #package是为了防止命名冲突(naming conflicts)

message Person {                 #定义message   
  required string name = 1;      #数字1是唯一的标签(unique tag)。     
  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];    #默认值是HOME
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}

一个message是有多个field组成的集合。message的field可以采用基础的数据类型,例如bool, int32, float, double和string。也可以使用其他message做为field的数据类型。甚至可以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值