Protobuf Github地址:https://github.com/protocolbuffers/protobuf/tree/master/python 先检查,本地的python版本:python -V 再检查,本地Protobuf版本:protoc --version 找到 *protobuf-masterpython,*代表你解压的位置 在cdm中切换到该位置,只有使用 python setup.py install 命令安装所需的依赖,如果安装了多个版本的pytho, 需要用你在目标项目中使用的python项目版本的python来执行这个命令。
syntax = "proto3";
package test;//这里使用文件名来做包名
message MainPack
{
string playerName = 1;
string playerPass = 2;
string ip = 3;
int32 id = 4;
}
放protoc的路径protoc-3.19.4-win64binprotoc.exe --python_out=目标输出路径 test.proto 在cmd中切换到 .proto 文件所在目录执行这条命令,执行完成后会在目标目录下生成 test_pb2.py
from protobuf import test_pb2 as DGP mainpack = DGP.MainPack() mainpack.playerName = "MOYV" mainpack.playerPass = "test" mainpack.ip = "192.168.1.1" mainpack.id = 2 send_msg =mainpack.SerializeToString() print(send_msg) # b'nx04MOYVx12x04testx1ax0b192.168.1.1 x02'
附上在C#中的解析
////// 接收到的消息长度 /// /// public void ReadBuffer(int length) { MainPack pack = (MainPack)MainPack.Descriptor.Parser.ParseFrom(buffer, 0, length); Debug.LogError(pack.Ip); }
QQ交流群(我不是群主):391584244



