Protobuf(Google Protocol Buffers)是google开发的的一套用于数据存储,网络通信时用于协议编解码的工具库.它和XML和Json数据差不多,把数据已某种形式保存起来.Protobuf相对与XML和Json的不同之处,它是一种二进制的数据格式,具有更高的传输,打包和解包效率
基础教程请参考:https://blog.csdn.net/u013210620/article/details/81317731
protoType类型如下:
double、float、int32、int64、uint32、uint64、sint32、sint64、fixed32、fixed64、sfixed32、sfixed64、bool、string、bytes
编译环境windows安装:
【下载protoc】
https://github.com/google/protobuf/releases
根据自己的平台下载对应的编译器,我的是win10-64位:
image.png解压到C:/Program Files下面:
image.png image.png
测试protoc:
新打开一个命令行:输入protoc --version,如果将输出版本号,说明protoc安装好了
image.png详情参考:https://blog.csdn.net/menghaocheng/article/details/80176763
linux\mac 参考: https://blog.csdn.net/u013210620/article/details/81317731
要使用先生成一个protoc文件
image.pngsyntax = "proto3";
package tutorial;
message Message{
string Accepter = 1;
bytes Protocal = 2;
bytes Data = 3;
string Sender = 4;
int64 SendTick = 5;
string LastID = 6;
}
生成protoc后使用命令生成.py文件 输出路径 本目录下
protoc .\Message.proto --python_out=./
另外protoc ./addressbook.proto –python_out=./这是输入的命令行指令,意思是在当前目录输出默认的即可。
image.png使用方法:
序列化SerializeToString()
反序列化 ParseFromString()
from protobuff import Message_pb2
image_file = Message_pb2.Message()
image_file.Accepter = '111'
test = image_file.SerializeToString()
print(test)
image.png
下面说下与C#结合的例子:
C# 中使用的是 protobuf-net 2.4.0
实体类:
[DataContract]
[ProtoContract]
public class Message : IMessage, IDisposable
{
/// <summary>
/// 频道ID或私信ID
/// </summary>
[DataMember]
[ProtoMember(1, IsRequired = false)]
public string Accepter
{
get; set;
}
[DataMember]
[ProtoMember(2, IsRequired = true)]
public byte Protocal
{
get; set;
}
[DataMember]
[ProtoMember(3, IsRequired = true)]
public byte[] Data
{
get; set;
}
/// <summary>
/// 发送者id
/// </summary>
[DataMember]
[ProtoMember(4, IsRequired = true)]
public string Sender
{
get; set;
}
/// <summary>
/// 发送时间
/// </summary>
[DataMember]
[ProtoMember(5, IsRequired = true)]
public long SendTick
{
get; set;
}
[DataMember]
[ProtoMember(6, IsRequired = true)]
public string LastID
{
get; set;
}
public void Dispose()
{
this.Accepter = null;
this.Protocal = 0;
if (Data != null)
Array.Clear(this.Data, 0, this.Data.Length);
this.Sender = null;
this.SendTick = 0;
}
}
C#客户端连接了Python websocket服务 并向其发送一条信息 内容:发送方,接收方,一张屏幕截图的流
Remote_Client_fubao.Model.Entity.Message msg = new Remote_Client_fubao.Model.Entity.Message
{
Accepter = "Python",
Sender = "C#",
Data = CompressHelper.Compress(ms.GetBuffer())
};
client._mCleint.ws.Send(SerializeHelper.ProtolBufSerialize(msg));
Python中接收到的信息:
image.png我们将其反序列化
image_file = Message_pb2.Message()
image_file.Accepter = '111'
test = image_file.SerializeToString()
print(test)
image_file.ParseFromString(bytes_data)
print(image_file.Accepter)
结果:
image.png
希望能对还在困扰的同学一点启发 感谢收看_
网友评论