当前位置:网站首页>Unity C# 网络学习(十二)——Protobuf生成协议
Unity C# 网络学习(十二)——Protobuf生成协议
2022-06-29 08:19:00 【帅_shuai_】
Unity C# 网络学习(十二)——Protobuf生成协议
一.安装
- 去Protobuf官网下载对应操作系统的protoc,用于将.proto文件生成对应语言的协议语言文件

- 由于我使用的是C#所以可以使用提供的C#的序列化反序列化的项目,然后自己编译出DLL放入Unity中使用

二.Protobuf 配置的规则(.proto文件的语法)
syntax = "proto3";//决定了proto文档的版本号
package GamePlayerTest;//命名空间
import "test2.proto";
//消息类
message TestMsg1 {
//成员类型 成员名称 唯一编号
//浮点数
float testF = 1;
double testD = 2;
//变长编码
//Protobuf会自动优化,可以尽量少的使用字节数,来存储内容
int32 testInt32 = 3; //不太适用于负数
int64 testInt64 = 4;
//更适用于负数
sint32 testSInt32 = 5;
sint64 testSInt64 = 6;
//无符号变长编码
uint32 testUInt32 = 7;
uint64 testUInt64 = 8;
//固定字节数类型
fixed32 testFixed32 = 9; //通常用于表示大于2的28次方的数 uint
fixed64 testFixed64 = 10; //通常用于表示大于2的56次方的数 ulong
sfixed32 testSFixed32 = 11; //int
sfixed64 testSFixed64 = 12; //long
//数组
repeated int32 arr_int32 = 13;
repeated string arr_string = 14;
//字典
map<int32,string> map1 = 15;
//枚举
TestEnum1 test_enum1 = 16;
//嵌套消息
message TestMsg2{
int32 test_int32 = 1;
}
TestMsg2 test_msg2 = 17;
//嵌套枚举
enum TestEnum2{
NORMAL = 0;
BOSS = 1;
}
TestEnum2 test_enum2 = 18;
GameSystemTest.HeartMsg heart_msg = 19;
}
enum TestEnum1{
NORMAL = 0;
BOSS = 5;
}
syntax = "proto3";
package GameSystemTest;
message HeartMsg{
int64 time = 1;
}
三.生成对应的C#代码
- 打开cmd窗口
- 进入protoc.exe所在文件夹(也可以直接拖入到cmd中)
- 输入转换指令
- protoc.exe -I=配置路径 =csharp_out=输出路径 配置文件名
四.封装快捷生成协议文件
public static class GenerateProtobuf
{
private const string ProtocPathExe = @"D:\Unity_Project\AgainLearnNet\Protobuf\protoc.exe";
private const string ProtoPath = @"D:\Unity_Project\AgainLearnNet\Protobuf\proto";
private const string OutPath = @"D:\Unity_Project\AgainLearnNet\Protobuf\csharp";
[MenuItem("Protobuf/GenerateCSharp")]
private static void GenerateCSharp()
{
DirectoryInfo directoryInfo = new DirectoryInfo(ProtoPath);
FileInfo[] fileInfos = directoryInfo.GetFiles();
foreach (var fileInfo in fileInfos)
{
if(fileInfo.Extension != ".proto")
continue;
Process cmd = new Process();
cmd.StartInfo.FileName = ProtocPathExe;
cmd.StartInfo.Arguments = $"-I={
ProtoPath} --csharp_out={
OutPath} {
fileInfo.Name}";
cmd.Start();
}
}
}
五.协议的序列化和反序列化
1.文本流
private void Start()
{
MyTestMsg myTestMsg = new MyTestMsg();
myTestMsg.PlayerId = 1;
myTestMsg.Name = "zzs";
myTestMsg.Friends.Add("wy");
myTestMsg.Friends.Add("pnb");
myTestMsg.Friends.Add("lzq");
myTestMsg.Map.Add(1,"ywj");
myTestMsg.Map.Add(2,"zzs");
string path = Application.persistentDataPath + "/testMsg.msg";
using (FileStream fs = new FileStream(path,FileMode.Create))
{
myTestMsg.WriteTo(fs);
}
MyTestMsg newMyTestMsg;
using (FileStream fs = new FileStream(path,FileMode.Open))
{
newMyTestMsg = MyTestMsg.Parser.ParseFrom(fs);
}
Debug.Log(newMyTestMsg.PlayerId);
Debug.Log(newMyTestMsg.Name);
Debug.Log(newMyTestMsg.Friends.Count);
Debug.Log(newMyTestMsg.Map[1]);
Debug.Log(newMyTestMsg.Map[2]);
}
2.内存流
private void Start()
{
MyTestMsg myTestMsg = new MyTestMsg
{
PlayerId = 1,
Name = "zzs"
};
myTestMsg.Friends.Add("wy");
myTestMsg.Friends.Add("pnb");
myTestMsg.Friends.Add("lzq");
myTestMsg.Map.Add(1,"ywj");
myTestMsg.Map.Add(2,"zzs");
byte[] buffer;
using (MemoryStream ms = new MemoryStream())
{
myTestMsg.WriteTo(ms);
buffer = ms.ToArray();
}
MyTestMsg newMyTestMsg;
using (MemoryStream ms = new MemoryStream(buffer))
{
newMyTestMsg = MyTestMsg.Parser.ParseFrom(ms);
}
Debug.Log(newMyTestMsg.PlayerId);
Debug.Log(newMyTestMsg.Name);
Debug.Log(newMyTestMsg.Friends.Count);
Debug.Log(newMyTestMsg.Map[1]);
Debug.Log(newMyTestMsg.Map[2]);
}
六.Protobuf的序列化和反序列化(优化调用方式)
private void Start()
{
MyTestMsg myTestMsg = new MyTestMsg
{
PlayerId = 1,
Name = "zzs"
};
myTestMsg.Friends.Add("wy");
myTestMsg.Friends.Add("pnb");
myTestMsg.Friends.Add("lzq");
myTestMsg.Map.Add(1,"ywj");
myTestMsg.Map.Add(2,"zzs");
byte[] buffer = myTestMsg.ToByteArray();
MyTestMsg newMyTestMsg = MyTestMsg.Parser.ParseFrom(buffer);
Debug.Log(newMyTestMsg.PlayerId);
Debug.Log(newMyTestMsg.Name);
Debug.Log(newMyTestMsg.Friends.Count);
Debug.Log(newMyTestMsg.Map[1]);
Debug.Log(newMyTestMsg.Map[2]);
}
边栏推荐
- P4769-[noi2018] bubble sort [combinatorics, tree array]
- P4769-[NOI2018]冒泡排序【组合数学,树状数组】
- 单例模式的理解
- Wallpaper applet source code double ended wechat Tiktok applet
- 实战回忆录从webshell开始突破边界
- Feature selection: maximum information coefficient (MIC) [used to measure the degree of correlation between two variables X and y, linear or nonlinear strength, commonly used for feature selection of
- 微积分学习
- [redis] redis6 learning framework ideas and details
- A high-frequency problem, three kinds of model thinking to solve this risk control problem
- 晋升或汇报,你真的把事情讲清楚了吗?
猜你喜欢
随机推荐
NP3 格式化输出(一)
[most complete] download and installation of various versions of PS and tutorial of small test ox knife (Photoshop CS3 ~ ~ Photoshop 2022)
ES6数据类型Map&Set
sql server 用 administrator 权限运行吗?还是以普通用户运行呢?
P6776-[noi2020] surreal tree
Core development board & debugger
C# 语音端点检测(VAD)实现过程分析
工厂模式和策略模式的区别
2022第六季完美童模 清远赛区 海选赛圆满落幕
2022年7月系统集成项目管理工程师认证招生简章
Measure the level of various chess playing activities through ELO mechanism
TypeScript 變量聲明 —— 類型斷言
“国防七校”之一西工大遭境外网络攻击
Simple use of vlookup function in Excel -- exact matching or approximate matching data
随心玩玩(三)Mirai框架QQ机器人
Sorting out easily confused words in postgraduate entrance examination English 【 flash 】
二手交易平台碳减排,有了评估标准
MySQL的分库分表策略及应用场景
Oracle subquery
How to recover data loss of USB flash disk memory card









