一. 环境 win7+anaconda+vscode+protobuf
二. 自行百度下载anaconda,也可以到我的第一篇文章网盘中下载安装
下载完后执行pip install protobuf安装protobuf相关的库
这个是我已安装好的。
三. 下载win7编译proto文件工具protoc-3.0.0-win32.zip,自行百度搜索下载,也可以到我的第一篇文章网盘中下载
四.编译两个proto文件
protoc --python_out=. TransportMessage.proto
protoc --python_out=. WeChatOnlineNoticeMessage.proto
没有报错说明ok的,注意要切换到bin目录下编译,或者设置环境变量,生成的.py文件复制到python项目中
五.泛型类Any的使用(直接进到源码中,any.proto中有例子)
TransportMessage.proto文件中代码:
syntax = "proto3";
import "google/protobuf/any.proto";//本来是这个路径(include/google/protobuf/any.proto),为方便将include中google目录拷贝出来
message TransportMessage {
int64 Id = 1; //消息Id(发送方内保持自增),请求中传入,响应中传回相同值
string AccessToken = 2; //设备通信token
EnumMsgType MsgType = 3; //承载的具体消息类型
google.protobuf.Any Content = 4; //具体的消息数据
int64 RefMessageId = 5; //如果是针对某个消息的响应,这里写对应请求的id
}
enum EnumMsgType {
UnknownMsg = 0; //未知消息
HeartBeatReq = 1001; //客户端发送的心跳包
MsgReceivedAck = 1002; //消息接收确认回复(接收或拒绝接收)
Error = 1003; //将错误单独提升为一种消息类型
WeChatOnlineNotice = 1020; //上线通知
}
WeChatOnlineNoticeMessage .proto文件代码:
syntax = "proto3";
import "TransportMessage.proto";
message WeChatOnlineNoticeMessage {
string WeChatId = 1;
string WeChatNo = 2;
string WeChatNick = 3;
EnumGender Gender = 4;
string Country = 5;
}
六.python中调用Any类型
def OnlineNotice_bytes():
print('上线通知...')
global Id
Id+=1
transportMessage = TransportMessage_pb2.TransportMessage()#注意括号不要掉了,
transportMessage.MsgType = 1020
transportMessage.Id = Id
transportMessage.AccessToken ="ac897dss"
weChatOnlineNotice = WeChatOnlineNoticeMessage_pb2.WeChatOnlineNoticeMessage()
weChatOnlineNotice.WeChatId = "id_123456789"
weChatOnlineNotice.WeChatNo = "qdj_cancle"
weChatOnlineNotice.WeChatNick = "昵称001"
weChatOnlineNotice.Gender = “男”
weChatOnlineNotice.Country = "中国"
#Any类型打包存在Content变量中
transportMessage.Content.Pack(weChatOnlineNotice)
return transportMessage.SerializeToString()
def OnlineNotice_message:
tmessage = TransportMessage_pb2.TransportMessage()
tmessage.ParseFromString(protobufdata)
i_id = tmessage.Id
i_msgtype = tmessage.MsgType
print('id:',i_id,'msgType:',i_msgtype)
if i_msgtype==0:
print('异常')
break
elseif i_msgtype==1010:
print('服务器接收到心跳包...')
elseif i_msgtype == 1020:
print('服务器接收到上线通知...')
online = WeChatOnlineNoticeMessage_pb2.WeChatOnlineNoticeMessage()
tmessage.Content.Unpack(online)
print('WeChatNo:'+online.WeChatNo,'WeChatId:'+online.WeChatId,'WeChatNick:'+online.WeChatNick)
总结:主要是Any类型的pack函数和Unpack函数
上一篇:【1】Python3学习
下一篇:【3】python3 socket传输protobuf数据