高性能服务器系列-第三章 Protobuf封装(C++/C#/Go)
前言
Protocol Buffers,是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。它不依赖于语言和平台并且可扩展性极强。数据在网络上传输,通常需要对数据进行编、解码。,ProtoBuf解析速度快、数据量少,数据结构丰富,支持多种编程语言,利用ProtoBuf对网络数据收发进行序列化和反序列化处理是一个比较好的方案。
一、Protobuf数据定义示例
- 基本类型:bool、uint32、int32、string、Float、Double定义和赋值较简单,不做特别介绍。
- protobuf里的string/bytes在C++接口里实现上都是std::string,不过对于string格式,会有一个utf-8格式的检查,当在确定字段编码格式后直接使用bytes,减少utf8编码的判断,效率上会有提高。同时如果数据中包含中文,如果用string出现乱码时,可采用bytes。
- 数组类型的数据采用repeated进行定义:
repeated string friends = 8;
介绍一下repeated类型的数据处理
c++:
testMsgRsp.add_friends("aa");
testMsgRsp.add_friends("bb");
C#:
msg_TestMsg.friends.Add("A");
msg_TestMsg.friends.Add("B");
- 数据结构类型数组的数据定义和处理:
message RoleInfoStc
{
required uint64 UserId = 1;
required string RoleName = 2;
}
...
required RoleInfoStc RoleInfo = 9;
数据处理示例:
c++:
RoleInfoStc* pfriendinfos1 = testMsgRsp.add_friendinfos();
pfriendinfos1->set_userid(1);
pfriendinfos1->set_rolename("cc");
C#:
msg_TestMsg.RoleInfo = new RoleInfoStc();
msg_TestMsg.RoleInfo.RoleName = "AA";
msg_TestMsg.RoleInfo.UserId = 1;
- 在一个proto文件中需要引用其它文件定义的类型时,需要通过inport进行导入
二、目录说明
- 解压ProtobufEncap.zip,可得到如下目录结构:
Client_c#: c#写的客户端
Server_c++: c++写的服务器端,
Server_go: go语言写的服务器端(以前项目中写的,本次没有进行联调)
三、Protobuf数据编译
-
进入ProtoGen目录,打开Build.bat文件,如下图所示:
CS_TARGET_PATH: c# 输出目录
C_TARGET_PATH: c/c++ 输出目录
GO_TARGET_PATH: go的输出目录 -
在ProtoGen目录创建*.proto文件,如Msg_Test.proto,双击Build.bat可对根目录下的全部*.proto文件进行编译。
四、客户端编译
-
编译工具
Client_c#编译工具Microsoft Visual Studio Professional 2022
-
编译后运行ProtobufEncap_Client.exe文件,界面如下:
四、c++服务端编译
- 编译环境
LSB Version: :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description: CentOS Linux release 8.5.2111
gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-4)
g++ (GCC) 8.5.0 20210514 (Red Hat 8.5.0-4)
cmake version 3.20.2 - 编译方法
将文件上传至centos系统,以”/xxfw/ProtobufEncap/”目录为例
cd /xxfw/ProtobufEncap/
ls
make
五、资源下载
- 获取示例工程资源
链接:https://pan.baidu.com/s/1tvcdC1wMi70s2uShAn6DXw?pwd=fy52
提取码:fy52 - 获取解压密码
链接:http://jiajiatong.store/target.html?id=4 - 上一章:
链接:高性能服务器系列-第二章 Mysql C++ 封装 - 下一章:
链接:高性能服务器系列-第四章 滑动窗口UDP