传输格式Protobuf之Protogen插件使用

Protobuf格式参考http://www.cnblogs.com/stephen-liu74/archive/2013/01/02/2841485.html

插件使用Protogen 

1,建立一个 bat

2, .bat 中 输入

protogen-i:test.proto   -o:test.cs

 protogen -i:Test1.proto -i:Test2.proto -i:Test3.proto -o:Output.cs -ns:com.fbmly.model

-i 是输入文件,可以有多个

-o 输出的cs文件, 只能有一个..如果-i有多个 会将所有的代码生成到这一个cs文件当中

-ns 命名空间   最好使用,如果不使用每次生成的默认命名空间是proto的文件名。

扫描二维码关注公众号,回复: 1094190 查看本文章

3,将 protobuffer-net拖入工程

GitHub地址:https://github.com/mgravell/protobuf-net/tree/master/src

然后将smcs拖入工程

重启 Unity3d

将生成的  protobbuffer.cs  托入工程 


具体实现如下。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using test;
using ProtoBuf;
using System;
using System.Text;
using System.IO;
public class TestBinary
{
    int id;
    string name;
    // 从类 到网络 数据
    byte[] GetNetBytes()
    {
        byte[] result;
        byte[] tmpInt = BitConverter.GetBytes(id);
        byte[] tmpName = Encoding.UTF8.GetBytes(name) ;
        int tmpLength = tmpInt.Length + tmpName.Length;
        result  = new byte[tmpLength];
        Buffer.BlockCopy(tmpInt,0,result,0,tmpInt.Length);
        Buffer.BlockCopy(tmpName, 0, result, tmpInt.Length, tmpName.Length);
        return result;
    }
    //  从 网络  到 类 
    TestBinary GetClass(byte[] byArr)
    {
        TestBinary testBinary = new TestBinary();
        testBinary.id = BitConverter.ToInt32(byArr,0);
        byte[] strBytes = new byte[byArr.Length -  4];
        Buffer.BlockCopy(byArr, 4, strBytes, 0, byArr.Length - 4);
        string   tmpName=   Encoding.UTF8.GetString(strBytes);
        testBinary.name = tmpName;
        return testBinary;
    }
}
public class TestProto : MonoBehaviour {
    //  讲  protobuff.cs  类 变成   bytes
    public static byte[] Serialize(IExtensible msg)
    {
        byte[] result;
        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, msg);
            result = stream.ToArray();
        }
        return result;
    }
    //  将 bytes 数组  变成 protobuff.cs 类 。
    public static IExtensible Deserialize<IExtensible>(byte[] message)
    {
        IExtensible result;
        using (var stream = new MemoryStream(message))
        {
            result = Serializer.Deserialize<IExtensible>(stream);
        }
        return result;
    }
	// Use this for initialization
	void Start () {
        TestMsg tmpMsg = new TestMsg();
        tmpMsg.id = 1000;
        tmpMsg.name = "1703";
        // 序列化  二进制 。
        byte[]   tmpBytes= Serialize(tmpMsg);
        // tmpBytes  从网络 来的 数据流 
         TestMsg   tmpTwo= Deserialize<TestMsg>(tmpBytes);
         Debug.Log("name==" + tmpTwo.name);		
	}





猜你喜欢

转载自blog.csdn.net/weixin_39706943/article/details/80489299
今日推荐