Protobuf-net

1. 概述 

        Protobuf是google开源的一个项目,用户数据序列化反序列化,google声称google的数据通信都是用该序列化方法。它比xml格式要少的多,甚至比二进制数据格式也小的多。

        Protobuf格式协议和xml一样具有平台独立性,可以在不同平台间通信,通信所需资源很少,并可以扩展,可以旧的协议上添加新数据

        Protobuf是在java和c++运行的,Protobuf-net当然就是Protobuf在.net环境下的移植。

        本次定义了一个User类做测试,包含了一些信息。

2. User.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;//引入

[ProtoContract]//须加才能使实例化出的对象序列化
public class User  {
    [ProtoMember(1)]//标识字段,标签为int型,不能重复
    public int ID { get; set; }
    [ProtoMember(2)]
    public string Username { get; set; }
    [ProtoMember(3)]
    public string Password { get; set; }
    [ProtoMember(4)]
    public int Level { get; set; }

    [ProtoMember(5)]
    public UserTyep _UserType { get; set; }

   public enum UserTyep
    {
        Master,
        Warrior
    }
	
}

3. TestProtobuf.cs

        做序列化与反序列化测试,其中场景中新建了两个按钮,点击时控制序列化与反序列化,需要做按钮事件绑定,另外有一个text用于显示反序列化出的内容。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using ProtoBuf;
using UnityEngine.UI;

public class TestProtobuf : MonoBehaviour {

    // Use this for initialization
    public Button createProtobufBtn;
    public Button loadProtobufBtn;

    public Text text;//显示反序列化后内容


    /// <summary>
    /// 序列化
    /// </summary>
    public void createProtobufBtnClick() {
        User user = new User();

        user.ID = 100;
        user.Username = "wangjun";
        user.Password = "88888888";
        user.Level = 99;
        user._UserType = User.UserTyep.Master;

        //FileStream fs = File.Create(Application.dataPath + "/user.bin");

        //Serializer.Serialize<User>(fs, user);

        //fs.Close();

        using (var fs = File.Create(Application.dataPath + "/user.bin"))
        {
            Serializer.Serialize<User>(fs, user);//序列化
        }
	}
	
	/// <summary>
    /// 反序列化
    /// </summary>
	public void loadProtobufBtnClick() {
        User user = null;

        using (var fs = File.OpenRead(Application.dataPath + "/user.bin"))
        {
            user = Serializer.Deserialize<User>(fs);//反序列化
        }
        text.text = user.ID + "," + user.Level + "," + user.Password + "," + user.Username + "," + user._UserType;
        Debug.Log(user.ID);
        Debug.Log(user.Level);
        Debug.Log(user.Password);
        Debug.Log(user.Username);
        Debug.Log(user._UserType);
    }
}



猜你喜欢

转载自blog.csdn.net/a962035/article/details/80672570