4 Star 7 Fork 1

itfriday / protocol-pack

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
LGPL-2.1

Protocol-Pack简介

Protocol-Pack(以下简称PP)是和google的Protocol Buffer(简称PB)类似的一种二进制数据交换的格式。它采用TT(L)V(即Tag-Type-Length-Value)的格式对数据信息进行编码,具有向前、向后兼容的特性。PP提供了多种语言的实现:C、C++、Java、Object-C,每种实现都尽量追求极简的编码风格,简单、干净、容易理解。

PP可以用于客户端与服务器之间的数据交换,也可以用于读、写配置文件,PP的几种语言的实现均提供了将数据结构或对象编码为XML格式的字符串的功能,C、C++的实现还提供了处理(或解码)XML元素数据的功能函数,读取XML配置文件的功能可以结合CXmlLoader和XmlLoader这两个项目来实现。

Protocol-Pack特点

  1. PP采用xml格式定义数据结构或对象,然后通过代码生成器生成的代码读写数据结构或对象。目前代码生成器可以生成C、C++、Java、Object-C这几种语言的代码。

  2. PP支持Union、Struct数据结构,还支持enum数据结构,支持采用marco定义宏或常量,支持数组等。PP支持的数据结构详情请见下面章节。

  3. PP的每种语言的实现均提供encode、decode、format、toXml这4个函数,其中encode函数将Union或Struct数据结构编码为二进制数据(大端序/网络序);decode函数将二进制数据解码为Union或Struct数据结构;format函数将数据结构编码为可读字符串,一般用于日志打印;toXml函数将数据结构编码为xml格式的字符串。

  4. 一般地,PP采用TTLV的格式对数据结构进行编码,但是针对数字类型的数据(比如32位整数),它们的长度是固定的,可以不必将长度编码到数据流中,所以它们的编码格式采用TTV。PP的编码格式详解请见下面章节。

  5. PP的C、C++实现,提供了读取XMl元素数据的功能函数,不过读取xml配置文件的功能需要结合CXmlLoader和XmlLoader这两个项目。

  6. PP的代码生成器采用python语言,不需要编译即可跨平台使用。代码生成器需在python2.4以上的环境下工作。

项目路径说明

  1. CMessage-Creator目录:代码生成器路径。代码生成器使用说明请见下面章节。

  2. CMessage目录:为C语言的实现提供支持的基础函数和测试代码。如果您的项目采用C语言,需要引入这些代码做为依赖项。

  3. JMessage目录:为Java语言的实现提供支持的基础类和测试代码。如果您的项目采用Java语言,需要引入这些基础类。

  4. Message目录:为C++语言的实现提供支持的基础类和测试代码。如果您的项目采用C++语言,需要引入这些基础类。

  5. OCMessage目录:为Object-C语言的实现提供支持的基础类和测试代码。如果您的项目采用Object-C语言,需要引入这些基础类。(需将pp目录下的代码拷贝到您的项目中)

  6. protocol-def目录:该目录下存放了一个数据结构定义的例子文件。

快速上手指南

要使用PP,您只需要完成如下几步操作:

  1. 采用XML编写结构或对象描述文件(或称为接口描述文件),定义数据结构或对象。您可以把数据结构定义在不同的文件中。数据结构或对象可以跨文件相互引用,当您需要引用其他文件中定义的结构时,不需要显式引入其他文件。您可以参考protocol-def目录中的例子msg.xml来编写结构定义文件。

  2. 采用代码生成器生成指定语言的数据结构或对象。代码生成器会为每个结构生成独立的文件。例如,假定您在描述文件中定义了一个名为Person的结构,且选择生成C语言代码,会生成Person.h和Person.c这两个文件。

  3. 将生成的代码及其依赖的基础代码添加到您的项目中。例如,假定您的项目采用C语言,除了需要把步骤2中生成的代码添加到项目中,还需要把CMessage目录中的代码添加到项目中。

  4. 代码生成器为每个结构体或对象均生成了encode、decode、format、toXml这4个函数(c语言的函数名会加上结构体名,例如结构体名若为Person,则这4个函数分别为person_field_encode、person_field_decode、person_field_format、person_field_to_xml),您可以调用encode函数结构或对象编码为二进制数据;调用decode函数将二进制数据解码为结构体或对象;当需要日志输出数据结构时,可以调用format函数,将数据结构编码为可读字符串;当需要将数据对象保存为xml文件时,可以调用toXml函数将数据编码为xml格式的字符串,再输出到文件。
       例如,在C语言下,将结构体Person编码为二进制数据的语句如下:
    PERSON stPerson;
    person_field_encode(&stPerson, 1, &stBa); // 第二个参数1是指Person的tag,第3个参数stBa是保存二进制数据的数组,有关于它的说明和初始化语句见下面的说明

从二进制数据解码Person结构体的语句如下:

    // 假定szBinData是待解码的二进制数据流,dwDataLen为二进制数据流的长度
    // 则将二进制解码为Person结构体的C语言如下:
    PERSON stPerson;
    memset(&stPerson, sizeof(stPerson), 0);
    person_field_decode(&stPerson, szBinData, dwDataLen);

注意:C、C++及Java语言,都提供了一个名为ByteArray的字节数组,它是一个辅组类,负责处理二进制数据,包括编码、解码等辅组功能。对C语言,字节数组的初始化语句如下:

    char szMsg1[1024]; // 定义字节数组的大小,注意C语言的字节数组不会自动扩展大小,您必须在初始化时为数组分配足够的大小
    BYTEARRAY stBa; // 定义字节数组
    INIT_BYTE_ARRAY(stBa, szMsg1, sizeof(szMsg1)); // 初始化字节数组

C++语言的字节数组初始化语句如下:

    MByteArray stBa; // 字节数组会自动扩展大小
    // 或
    MByteArray stBa(1024); // 初始化时,指定初始缓存大小,如果缓存不够,将自动扩展大小
    // 因为字节数组在扩展大小时,会重新申请内存,并将之前的数据拷贝到新的内存中,为避免频繁内存操作,建议采用指定初始缓存大小的形式。

Java语言的字节数组初始化语句如下:

    ByteArray ba = new ByteArray(); // 字节数组会自动扩展大小
    // 或
    ByteArray ba = new ByteArray(1024); // 初始化时,指定初始缓存大小,如果缓存不够,将自动扩展大小
    // 因为字节数组在扩展大小时,会重新申请内存,并将之前的数据拷贝到新的内存中,为避免频繁内存操作,建议采用指定初始缓存大小的形式。

Demo

  1. 每种语言都提供了例子,放在语言对应的test目录下。其中:
        CMessage/test/main.c,为C语言例子程序
        JMessage/com/itfriday/test/Test.java,为Java语言例子程序
        Message/test/main.cpp,为C++语言例子程序

  2. 要运行Demo程序,您必须先执行目录下的gen.bat(Windows下)或gen.sh(Linux下)程序生成相应的代码。gen.bat/gen.sh程序会调用PP代码生成器将protocol-def目录下定义的msg.xml转变为结构或对象。

  3. 接着,您需要将生成的代码编译为可执行程序,然后执行。
        针对C语言,在Linux下,切换到CMessage/test目录,执行Make命令,即可编译出名为Message的可执行程序。
        针对C++语言,在Linux下,切换到Message/test目录,执行Make命令,即可编译出名为Message的可执行程序。
        针对Java语言,切换到JMessage目录,执行build命令,可以执行编译。
        针对Object-C语言,切换到OCMessage目录,使用XCode打开项目,编译、运行。

  4. 例子程序执行后的输出见下图:

// 将结构体编码为可读形式的输出
[CsMsgResponse]
    Eno = 0
    Cmd = 2
    [RespData]
        [GetFriends]
            FriendNumber = 2
            [FriendInfo]
                GID = 305419896
                FriendName = ErisenXu
                FriendImage = http://www.qq.com/erisenxu.jpg
            [FriendInfo]
                GID = 2018915346
                FriendName = xy
                FriendImage = http://www.qq.com/xy.jpg
            TypeNumber = 3
            Types = 3430008
            Types = 9004884
            Types = 2464388554683811993
// 将结构体编码为XML形式的输出
<CsMsgResponse>
    <Eno>0</Eno>
    <Cmd>2</Cmd>
    <RespData>
        <GetFriends>
            <FriendNumber>2</FriendNumber>
            <FriendInfo>
                <GID>305419896</GID>
                <FriendName>ErisenXu</FriendName>
                <FriendImage>http://www.qq.com/erisenxu.jpg</FriendImage>
            </FriendInfo>
            <FriendInfo>
                <GID>2018915346</GID>
                <FriendName>xy</FriendName>
                <FriendImage>http://www.qq.com/xy.jpg</FriendImage>
            </FriendInfo>
            <TypeNumber>3</TypeNumber>
            <Types>3430008</Types>
            <Types>9004884</Types>
            <Types>2464388554683811993</Types>
        </GetFriends>
    </RespData>
</CsMsgResponse>
// 将结构体编码为二进制流形式的输出
0000   00 01 0b 00 00 00 d3 00  01 03 00 00 00 02 03 00   ........ ........
0010   02 00 03 0b 00 00 00 c2  00 02 0b 00 00 00 bb 00   ........ ........
0020   01 02 02 00 02 0c 00 00  00 82 00 02 00 02 0b 00   ........ ........
0030   00 00 3f 00 01 08 00 00  00 00 12 34 56 78 00 03   ..?..... ...4Vx..
0040   09 00 00 00 08 45 72 69  73 65 6e 58 75 00 04 09   .....Eri senXu...
0050   00 00 00 1e 68 74 74 70  3a 2f 2f 77 77 77 2e 71   ....http ://www.q
0060   71 2e 63 6f 6d 2f 65 72  69 73 65 6e 78 75 2e 6a   q.com/er isenxu.j
0070   70 67 00 02 0b 00 00 00  33 00 01 08 00 00 00 00   pg...... 3.......
0080   78 56 34 12 00 03 09 00  00 00 02 78 79 00 04 09   xV4..... ...xy...
0090   00 00 00 18 68 74 74 70  3a 2f 2f 77 77 77 2e 71   ....http ://www.q
00a0   71 2e 63 6f 6d 2f 78 79  2e 6a 70 67 00 03 02 03   q.com/xy .jpg....
00b0   00 04 0c 00 00 00 23 00  03 00 04 08 00 00 00 00   ......#. ........
00c0   00 34 56 78 00 04 08 00  00 00 00 00 89 67 54 00   .4Vx.... .....gT.
00d0   04 08 22 33 44 55 66 77  88 99                     .."3DUfw ..
// 解码为结构体后,将结构体输出为可读形式
[CSMsgResponse]
    Eno = 0
    Cmd = 2
    [RespData]
        [GetFriends]
            FriendNumber = 2
            [FriendInfo]
                GID = 305419896
                FriendName = ErisenXu
                FriendImage = http://www.qq.com/erisenxu.jpg
            [FriendInfo]
                GID = 2018915346
                FriendName = xy
                FriendImage = http://www.qq.com/xy.jpg
            TypeNumber = 3
            Types = 3430008
            Types = 9004884
            Types = 2464388554683811993

接口描述文件

要使用PP,最重要的就是采用XML定义结构或对象描述文件,或者称为接口描述文件。本章将详细介绍如何定义一个接口描述文件。

  1. 描述文件基本结构。

    描述文件采用标准的XML编写,必须包含一个名为field-config的根节点。文件中定义的其他宏、结构体、枚举类型,都是field-config的子节点。

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<field-config version="1">
    <!-- 在这里定义宏、枚举、结构体 等-->
    ......
</field-config>
  1. 如何定义宏

    采用macro定义宏。暂时只支持定义整数类型的宏。name属性指定宏的名字,value指定宏的值,desc指定宏的描述:

<macro name="MAX_URL_LEN"            value='256'           desc='最大URL地址长度' />
  1. 如何定义枚举类型

    采用enum定义枚举。name属性指定枚举名字,desc属性指定枚举的描述,macro子节点定义枚举包含的元素。enum可以包含一个或多个macro子节点:

<enum name="CS_MSG_TYPE_"  desc="客户端消息类型" >
    <macro name="CS_MSG_LOGIN"                              value="1"        desc="登录" />
    <macro name="CS_MSG_GET_FRIEND_LIST"                    value="2"        desc="获取好友列表" />
</enum>
  1. 如何定义Struct结构

    采用struct定义一个结构体。name属性指定结构名称,desc属性指定结构描述,field子节点定义结构包含的子元素。struct可以包含一个或多个field子节点。
    field子节点包含如下属性:

属性名 属性说明 是否必须指定
name 子元素名
type 子元素类型,可取值为:uchar、char、ushort、short、uint、int、ulong、long、string、bytes、array、其他用struct或union定义的结构
tag 子元素的标签。为保证协议前后兼容性,每个子元素的标签必须在其所属结构体的作用域中是唯一的
subtype 子元素类型,可取值为:uchar、char、ushort、short、uint、int、ulong、long、其他用struct或union定义的结构。注意subtype不支持string、bytes、array,即数组元素不支持直接采用字符串、字节数组和数组,可以将它们定义到结构体中然后指定结构体为数组的元素(见后面的例子)。 当type=array,表示子字段为数组时,必须指定subtype
count 用来指定字符串或数组元素的最大数量 当type=array或type=string或type=bytes时,必须指定count
refer 数组有效元素数量,取值必须是结构体中定义的一个整形元素 当type=array或type=bytes时,必须指定refer
select union元素选择器,取值必须是结构体中定义的一个整形元素 当type是一个union类型的结构体时,必须指定select
desc 子元素的描述
一个结构体的例子如下:
    <struct name='FriendInfo' desc='好友信息'>
        <field    name="GID"            type="ulong"         tag="1"                                            desc="好友GID" />
        <field    name="FriendName"     type="string"        tag="3"            count="MAX_NAME_LEN"            desc="好友名称" />
        <field    name="FriendImage"    type="string"        tag="4"            count="MAX_URL_LEN"             desc="好友头像URL地址" />
    </struct>
它定义了一个名为FriendInfo的结构体,包含GID、FriendName、FriendImage这3个子字段,类型分别是ulong,string和string,其中FriendName的最大长度是MAX_NAME_LEN,FriendImage的最大长度是MAX_URL_LEN。MAX_NAME_LEN和MAX_URL_LEN是用macro定义的宏。如果是C语言,FriendInfo将被代码生成器转变为C语言的结构体:
struct tagFriendInfo
{
    U64 ullGID;                      // 好友GID
    char szFriendName[MAX_NAME_LEN]; // 好友名称
    char szFriendImage[MAX_URL_LEN]; // 好友头像URL地址
};
typedef struct tagFriendInfo  FRIENDINFO;
typedef struct tagFriendInfo* LPFRIENDINFO;
当一个结构体被定义后,它将成为一个新的类型,可以被其他结构体引用。使用type或subtype即可以引用它,例子如下:
    <struct name='FriendInfoList' desc='Just a Test Message object'>
        <field    name="FriendNumber"    type="uchar"        tag='1'            default="0"                        desc="好友数量" />
        <field    name="FriendInfo"      type="array"        tag="2"            subtype='FriendInfo'               count='MAX_FRIEND_NUMBER'      refer='FriendNumber'    desc="好友列表" />
        <field    name="TypeNumber"      type="uchar"        tag='3'            default="0"                        desc="类型数量" />
        <field    name="Types"           type="array"        tag="4"            subtype='ulong'                    count='MAX_TYPE_NUMBER'        refer='TypeNumber'      desc="类型列表" />
    </struct>
这个例子定义了一个名为FriendInfoList的结构,它的子字段FriendInfo是一个数组,数组元素类型是FriendInfo,数组的最大元素数量由MAX_FRIEND_NUMBER指定,数组的有效元素数量由字段FriendNumber决定(注意这里的refer,它指定了数组FriendInfo的有效元素数量,由字段FriendNumber决定)。如果是C语言,FriendInfoList将被代码生成器转变为C语言的结构体如下:
struct tagFriendInfoList
{
    U8 bFriendNumber;                            // 好友数量
    FRIENDINFO astFriendInfo[MAX_FRIEND_NUMBER]; // 好友列表
    U8 bTypeNumber;                              // 类型数量
    U64 astTypes[MAX_TYPE_NUMBER];               // 类型列表
};
typedef struct tagFriendInfoList  FRIENDINFOLIST;
typedef struct tagFriendInfoList* LPFRIENDINFOLIST;
  1. 如何定义Union联合

    定义联合和定义结构体的语法类似,只是联合采用union来定义,name属性指定联合名称,desc属性指定联合描述,field子节点定义联合包含的子元素。union可以包含一个或多个field子节点。field子节点包含属性和struct节点的field子节点包含的属性一样,见上表。

一个联合的例子如下:

    <union name='CsRequestData' desc='客户端响应协议消息结构体'>
        <field    name="Login"         type="LoginRequest"            tag='CS_MSG_LOGIN'                    desc='客户端登录请求' />
        <field    name="GetFriends"    type="char"                    tag='CS_MSG_GET_FRIEND_LIST'          desc='获取好友列表请求' />
    </union>

若转变为C语言,对应的代码如下:

struct tagCsRequestData
{
    U16 nSelector;  // 联合的选择器,由代码生成器自动添加。
    union
    {
        LOGINREQUEST stLogin; // 客户端登录请求
        S8 chGetFriends;     // 获取好友列表请求
    };
};
typedef struct tagCsRequestData  CSREQUESTDATA;
typedef struct tagCsRequestData* LPCSREQUESTDATA;

这里,联合的选择器是由代码生成器自动添加的,当它值与联合中的某个字段的tag相同时,联合将用于保存该字段的值。即:

if (nSelector == CS_MSG_LOGIN) {
    // tagCsRequestData代表了stLogin
} else if (nSelector == CS_MSG_GET_FRIEND_LIST) {
    // tagCsRequestData代表了chGetFriends
}

和struct结构体类似,当一个联合被定义后,它将成为一个新的类型,可以被其他结构体引用。使用type或subtype即可以引用它,但是必须为它指定select属性,例子如下:

    <struct name="CsMsgRequest"    version="1"        desc="客户端请求协议" >
        <field name="GID"            type="ulong"            tag="1"        desc="玩家GID" />
        <field name="Cmd"            type="short"            tag="2"        desc="消息命令字" />
        <field name="ReqData"        type="CsRequestData"    tag="3"        desc="消息结构体"    select="Cmd"/>
    </struct>

对应的C语言如下:

struct tagCsMsgRequest
{
    U64 ullGID;              // 玩家GID
    S16 shCmd;               // 消息命令字
    CSREQUESTDATA stReqData; // 消息结构体
};
typedef struct tagCsMsgRequest  CSMSGREQUEST;
typedef struct tagCsMsgRequest* LPCSMSGREQUEST;

这个例子定义了一个CsMsgReuqest结构,它的子字段ReqData的类型是CsRequestData,它是一个联合,它的选择器由select指定为Cmd,因此当Cmd==CS_MSG_LOGIN时,ReqData将代表stLogin字段,当Cmd==CS_MSG_GET_FRIEND_LIST时,ReqData将代表chGetFriends字段。

代码生成器使用说明

代码生成器位于CMessage-Creator目录,它是python编写的工具,不需要编译可以跨平台使用。它需要python2.4以上的环境。

代码生成器的主程序是generator.py,执行python generator.py --help可以查看帮助。

Description: message generator.
Version: 1.0.0.0
Usage: python generator.py [-?] [-h] [-s DIRECTORY] [-d DIRECTORY]
                           [-l {c, cpp, java, oc}] [-m FILE_NAME] [-p PACKAGE_NAME]
optional arguments:
  -?, -h, --help	Show this help information
  -s DIRECTORY, --srcpath DIRECTORY
			Set protocol define file search directory
  -l {c, cpp, java, oc}, --language {c, cpp, java, oc}	
			Major programming language you want to use, should be
			[c|cpp|java|oc]
  -d DIRECTORY, --directory DIRECTORY
			Set generate project directory for project
  -m FILE_NAME
			Set generate macro file name
  -p PACKAGE_NAME
			Set package for java
Example:
  python generator.py --help
  python generator.py -s . -d ../test -l c -m StarMacro

可选输入参数说明如下:

可选参数:
  -?, -h, --help	显示本程序的帮助信息
  -s DIRECTORY, --srcpath DIRECTORY
			指定接口描述文件所在路径
  -l {c, cpp, java, oc}, --language {c, cpp, java, oc}	
			代码生成器生成的代码语言种类,目前可选c、cpp、java,和oc
  -d DIRECTORY, --directory DIRECTORY
			设置代码生成路径
  -m FILE_NAME
			设置宏定义文件名称
  -p PACKAGE_NAME
			设置包名,仅仅对java语言有用

但是针对数字类型的数据(比如32位整数),它们的长度是固定的,可以不必将长度编码到数据流中,所以它们的编码格式采用TTV 编码规则详解

PP采用TT(L)V的格式对数据结构进行编码,其中:

    T(Tag),字段标签,用来唯一标识或区别一个字段。编码为二进制时,占用2个字节长度。

    T(Type),字段类型,用来标识字段类型。编码为二进制时,占用1个占用长度。

    L(Length),字段的值(Value)的长度。当字段类型(Type)为整形时,不包含长度。编码为二进制时,长度占用4个字节。

    V(Value),字段的值。所占字节长度由L(Length)指定

PP支持的字段类型包括:

类型 Type的值 字节长度 类型说明
char 1 1 有符号整数,占1个字节
uchar 2 1 无符号整数,占1个字节
short 3 2 有符号整数,占2个字节
ushort 4 2 无符号整数,占2个字节
int 5 4 有符号整数,占4个字节
uint 6 4 无符号整数,占4个字节
long 7 8 有符号整数,占8个字节
ulong 8 8 无符号整数,占8个字节
string 9 不固定 字符串类型,长度由Length字段指定
bytes 10 不固定 字节数组类型,长度由Length字段指定(当前暂不支持)
结构体类型 11 不固定 在接口描述文件中,采用Struct和Union定义的结构体类型,长度由Length字段指定
array 12 不固定 数组类型,长度由Length字段指定

举个例子,Tag为1,类型为ushort,16进制值为0x1234的整数,编码为二进制为:

00 01 04 12 34 

Tag为4,类型为string的字符串http://www.qq.com/xy.jpg,编码为二进制为:

00 04 09 00 00 00 18 68 74 74 70  3a 2f 2f 77 77 77 2e 71 71 2e 63 6f 6d 2f 78 79  2e 6a 70 67

其中:

	00 04 为Tag
	09 为类型
	00 00 00 18 为字符串长度,这里长度是0x18,即24
	68 74 74 70  3a 2f 2f 77 77 77 2e 71 71 2e 63 6f 6d 2f 78 79  2e 6a 70 67为字符串的值

而复合结构体的编码为各子字段编码的拼接,例如,假定一个结构体包含以上两个字段(即一个ushort一个string),则结构体编码为二进制为:

00 02 0b 00 00 00 24 00 01 04 12 34 00 04 09 00 00 00 18 68 74 74 70  3a 2f 2f 77 77 77 2e 71 71 2e 63 6f 6d 2f 78 79  2e 6a 70 67

其中:

	00 02 为结构体Tag
	0b 为类型
	00 00 00 24 为结构体长度,这里长度是0x24,即36个字节

00 01 为第一个子字段的Tag 04 为类型 12 34为第一个字段的值

00 04 为第二个子字段的Tag 09 为类型(字符串) 00 00 00 18 为字符串长度,这里长度是0x18,即24 68 74 74 70 3a 2f 2f 77 77 77 2e 71 71 2e 63 6f 6d 2f 78 79 2e 6a 70 67为字符串的值

数组字段的编码,编码Value前,会编码数组数量,数组数量会占用2字节。例如,假定一个数组元素为上面定义的结构体,且数量为2,编码为二进制为:

00 03 0c 00 00 00 58 00 02
00 03 0b 00 00 00 24 00 01 04 12 34 00 04 09 00 00 00 18 68 74 74 70  3a 2f 2f 77 77 77 2e 71 71 2e 63 6f 6d 2f 78 79  2e 6a 70 67
00 03 0b 00 00 00 24 00 01 04 12 34 00 04 09 00 00 00 18 68 74 74 70  3a 2f 2f 77 77 77 2e 71 71 2e 63 6f 6d 2f 78 79  2e 6a 70 67

其中:

	00 03 为数组Tag
	0c 为类型
	00 00 00 58 为数组长度,这里长度是0x58,即88个字节
	00 02 为数组元素数量,这里数量为2
	其他两行编码为数组元素结构体的编码。注意这里数组元素结构体的Tag与数组的Tag相同,都为0x03

联合(union)的编码规则和符合结构体的编码规则一样,只是要注意一点的是,union的标签Tag即是它的选择器selector,也即是它的有效子字段的标签。只有Tag对应的union子字段会被编码,其他无效的子字段不会被编码。

例如,对于联合CsRequestData

    <union name='CsRequestData' desc='客户端响应协议消息结构体'>
        <field    name="Login"         type="LoginRequest"            tag='CS_MSG_LOGIN'                    desc='客户端登录请求' />
        <field    name="GetFriends"    type="char"                    tag='CS_MSG_GET_FRIEND_LIST'          desc='获取好友列表请求' />
    </union>

若其字段Login有效,则编码为二进制时,CsRequestData的tag将为CS_MSG_LOGIN,只有Login子字段会被编码;

若其字段GetFriends有效,则编码为二进制时,CsRequestData的tag为CS_MSG_GET_FRIEND_LIST,只有GetFriends子字段会被编码

GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. (This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.) Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. {signature of Ty Coon}, 1 April 1990 Ty Coon, President of Vice That's all there is to it!

简介

Protocol-Pack(以下简称PP)是和google的Protocol Buffer(简称PB)类似的一种二进制数据交换的格式。它采用TT(L)V(即Tag-Type-Length-Value)的格式对数据信息进行编码,具有向前、向后兼容的特性。PP提供了多种语言的实现:C、C++、Java、Object-C,每种实现都尽量追求极简的编码风格,简单、干净、容易理解。 PP可以用于客户端与服务器之间的数据交换,也可以用于读、写配置文件,PP的几种语言的实现均提供了将数据结构或对象编码为XML格式的字符串的功能,C、C++的实现还提供了处理(或解码)XML元素数据的功能函数,读取XML配置文件的功能可以结合CXmlLoader和XmlLoader这两个项目来实现。 展开 收起
Objective-C 等 6 种语言
LGPL-2.1
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Objective-C
1
https://gitee.com/itfriday/protocol-pack.git
git@gitee.com:itfriday/protocol-pack.git
itfriday
protocol-pack
protocol-pack
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891