protobuf-net与FlatBuffers

protobuf-net

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

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

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

1、先下载protobuf-net

2、新建一个控制台应用程序,并引入protobuf-net里的protobuf-net.dll

3、编写代码

类前加上ProtoContract Attrbuit,成员加上ProtoMember Attribute即可,其中ProtoMember需要一个大于0的int类型的值,原则上这个int类型没有大小限制,但建议从1开始,这是一个良好的习惯,另外这个参数必需是这个类成员的唯一标识,不可重复

   [ProtoContract]
    class MySocketModel
    {
        [ProtoMember(1)]
        public int type;

        [ProtoMember(2)]
        public int area;

        [ProtoMember(3)]
        public int command;

        [ProtoMember(4)]
        public string message;
    }
class Program
    {
        static void Main(string[] args)
        {
            MySocketModel sm = new MySocketModel()
            {
                type = 111,
                area = 222,
                command = 333,
                message = "okokokokokokokokok"
            };
Console.WriteLine(
"==================序列化=================="); //Protobuffer序列话 MemoryStream ms = new MemoryStream(); Serializer.Serialize<MySocketModel>(ms, sm); byte[] result = new byte[ms.Length]; Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length); Console.WriteLine("Protobuffer序列化的大小为:" + (result.Length)); //28 //二进制序列话 byte[] bb = MySerilize(sm); Console.WriteLine("二进制序列化的大小为:" + (bb.Length)); //31
Console.ReadKey(); Console.WriteLine(
" =================反序列化================="); Stream stream = new MemoryStream(result); MySocketModel st = Serializer.Deserialize<MySocketModel>(stream); Console.WriteLine("type:" + st.type + " area:" + st.area + " command:" + st.command + " rr:" + st.message); Console.ReadKey(); } public static byte[] MySerilize(object t) { MySocketModel sm = t as MySocketModel; using (MemoryStream ms = new MemoryStream()) { BinaryWriter writer = new BinaryWriter(ms); writer.Write(sm.type); writer.Write(sm.area); writer.Write(sm.command); writer.Write(sm.message); byte[] result = new byte[ms.Length]; Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length); return result; } } }

之前在WIN7,安卓上使用都正常。发布到 IPAD MINI2 上是发现有问题,表现如下:
有时可以正常使用,但似乎一开始会被卡一会。
有时完全无法正常使用,反序列化的时候会抛异常出来。
 
查网络上资料,觉得是否应该在发布到IOS时设置里要改一下。
有一个选择支持“.Net 2.0 subset模式”或“.Net 2.0模式”的选项,默认是“.Net 2.0 subset模式”,网上说要改成“.Net 2.0模式”
改了后,发现还是抛异常,不过现在报“JIT异常”,发现U3D不支持。
 
所以最后采用的方法是
1. 下载protobuf-net源码, 把其中“protobuf-net”文件夹 拷贝到unity 即可 . (我从svn下载好之后有很多文件夹的,比如protobuf-net,protobuf-net_IKVM,protobuf-net_MonoDroid,protobuf-net_Phone7 ,ProtoGen,QuickStart 等等 ,只复制那个protobuf-net就可以 。) 
地址:https://github.com/mgravell/protobuf-net
2. 建立一个新的文件smcs.rsp  ,内容是-unsafe ,前后都无空格。该文件放在 Assets 目录下。
3. 把工程设置为.Net 2.0 subset
4. 重启Unity 
这样就搞定了。 

FlatBuffers(更适用于移动设备)

原文地址:https://www.cnblogs.com/MrZivChu/p/buffer.html