类似于Json的一个序列化与反序列化数据的数据传输工具 Protobuffer自带编辑器.exe文件(protoc)该工具跨语言跨平台 与Json相比数据量更小 效率更高 因为Json中引号冒号逗号等格式也是需要传送的 传送就占用了数据中的字节数
///生成proto文件
namespace common
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@“user”)]
public partial class user : global::ProtoBuf.IExtensible
{
public user() {}
private string _username;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@“username”, DataFormat = global::ProtoBuf.DataFormat.Default)]
public string username
{
get { return _username; }
set { _username = value; }
}
private string _password;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@“password”, DataFormat = global::ProtoBuf.DataFormat.Default)]
public string password
{
get { return _password; }
set { _password = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
Protobuffer语法 用required修饰的变量必须传值 如果用optional修饰则不必传值 用repeated修饰的变量则类似于c#中的list集合 重复传值且记录之前的值 message则相当于c#中的类 package则相当于命名空间 完成了一个.proto文件后用Protobuffer的编辑器编辑完成生成c#文件 再导入Protobuffer的.net(dll)包则可使用 序列化与反序列化时封装ProtobufferUtils工具类
class ProtobufferUtils
{
public static byte[] Serialize(T data)
{
using(MemoryStream ms=new MemoryStream())
{
Serializer.Serialize(ms, data);
return ms.ToArray();
}
}
public static T Deserialize(byte[] data)
{
using(MemoryStream ms = new MemoryStream(data))
{
T t = Serializer.Deserialize(ms);
return t;
}
}
}
使用内存流用Serializer.Serialize序列化写入数据到缓存数组 反序列化时使用内存流加载缓存数组用Serializer.Deserialize反序列化返回对象
当使用各种流时 使用完毕需要手动关闭(close)使用using()将流传入则默认执行结束自动关闭
附上实现脚本
class Program
{
static void Main(string[] args)
{
user u = new user();
u.username = “少年阿刚”;
u.password = “admin”;
byte[] b = ProtobufferUtils.Serialize(u);
File.WriteAllBytes(“a”, b);
byte[] data = File.ReadAllBytes(“a”);
Console.WriteLine(data.Length);
user newUser = ProtobufferUtils.Deserialize(data);
Console.WriteLine("{0}:{1}" ,newUser.password,newUser.username);
Console.ReadKey();
}
}
UnityProtobuffer的应用
最新推荐文章于 2024-05-16 21:53:10 发布