美文网首页
ProtoBuf使用框架

ProtoBuf使用框架

作者: 醉酒青牛_fa4e | 来源:发表于2019-04-17 00:24 被阅读0次

using ProtoBuf;
using System.IO;
using UnityEngine;

/// <summary>
/// 继承此类,标记为protobuf
/// 提供序列化和反序列化两个函数
/// </summary>
[ProtoContract]
public class ProtoBase : MonoBehaviour {
/// <summary>
/// 序列化类
/// </summary>
/// <param name="type">类的对象</param>
/// <returns></returns>
public byte[] Serialize(ProtoBase tmp)
{
byte[] result;
using (MemoryStream stream = new MemoryStream())
{
Serializer.Serialize(stream, tmp);
result = stream.ToArray();
}
return result;
}
/// <summary>
/// 将流反序列化为对象
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static ProtoBase DeSerialize(byte[] buffer)
{
using (MemoryStream stream = new MemoryStream(buffer))
{
ProtoBase tmp = Serializer.Deserialize<ProtoBase>(stream);
return tmp;
}
}
}


using ProtoBuf;

/// <summary>
/// 要发送的类继承ProtoBase
/// </summary>
[ProtoContract]
public class Person :ProtoBase {

[ProtoMember(1)]
private string myName;
public string Name
{
    get
    {
        return myName;
    }
    set
    {
        myName = value;
    }
}
[ProtoMember(2)]
private int age;
public int  Age
{
    get
    {
        return age;
    }
    set
    {
        age = value;
    }
}
public Person() { }
public  Person(string name,int age)
{
    Name = name;
    Age = age;
}

}


using UnityEngine;
/// <summary>
/// 使用类
/// </summary>
public class ManagerSenProtoBuf : MonoBehaviour {

Person person;

byte[] buffer;


void Start () {
     person = new Person("小黑", 20);
}

private void Update()
{
    if (Input.GetKey(KeyCode.A))
    {
        buffer=person.Serialize(person);
        Debug.Log(buffer.Length);
    }
    if (Input.GetKey(KeyCode.B))
    {
        Person.DeSerialize(buffer);
        Debug.Log("名字+" + person.Name + "年龄+" + person.Age);
    }
}

}

相关文章

网友评论

      本文标题:ProtoBuf使用框架

      本文链接:https://www.haomeiwen.com/subject/cmqxbqtx.html