コード例 #1
0
    //void Update()
    //{
    //    if (NetworkController.Instance != null && serverSessionId > 0)
    //    {
    //        // 在网络Session池中取消息
    //        while ((proto = NetworkController.Instance.GetMessage(serverSessionId)) != null)
    //        {

    //            if (proto.GetID().BodyType == typeof(LuaProtoBody))
    //            {
    //                ByteBuffer buffer = new ByteBuffer(((LuaProtoBody)proto.GetBody()).byteArray);
    //                Util.CallMethod("Network", "OnSocket", (int)proto.GetID(), buffer);
    //                Debug.Log(">>>>>>>>>>>>>>>>>>>" + ((LuaProtoBody)proto.GetBody()).byteArray.ToString());
    //            }
    //            else
    //            {

    //                UnityEngine.Debug.Log(serverSessionId + "Received Proto Id " + proto.GetID());
    //                TestProtoBody testBody = proto.GetBody() as TestProtoBody;
    //                if (testBody != null)
    //                    UnityEngine.Debug.Log(serverSessionId + "Received Proto Body " + testBody.id + " " + testBody.name);

    //            }

    //        }
    //    }
    //}

    // 将消息序列化为二进制的方法
    // < param name="model">要序列化的对象< /param>
    private byte[] Serialize(TestProtoBody model)
    {
        try
        {
            //涉及格式转换,需要用到流,将二进制序列化到流中
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                //使用ProtoBuf工具的序列化方法
                ProtoBuf.Serializer.Serialize <TestProtoBody>(ms, model);
                //定义二级制数组,保存序列化后的结果
                byte[] result = ms.ToArray();
                //将流的位置设为0,起始点
                ms.Position = 0;
                ms.Write(BitConverter.GetBytes((Int32)result.Length), 0, sizeof(UInt32));
                //将流中的内容读取到二进制数组中
                ms.Write(result, 0, result.Length);

                result = ms.ToArray();
                return(result);
            }
        }
        catch (Exception ex)
        {
            Debug.Log("序列化失败: " + ex.ToString());
            return(null);
        }
    }
コード例 #2
0
        // 将二进制序列化为ProtoBody类的方法
        // < param name="model">要序列化的对象< /param>
        void Deserialize(byte[] bytes)
        {
            ByteBuffer buffer = new ByteBuffer(bytes);
            int        mainid = buffer.ReadShort();        //类型id

            byte[] byteArray = buffer.ReadBytes();         //消息内容

            MemoryStream memStream = new MemoryStream();

            memStream.Seek(0, SeekOrigin.End);
            memStream.Write(byteArray, 0, byteArray.Length);
            memStream.Seek(0, SeekOrigin.Begin);

            TestProtoBody pbody = ProtoBuf.Serializer.Deserialize <TestProtoBody>(memStream);

            if (pbody != null)
            {
                //Debug.Log("成功了--------" + pbody.id + pbody.name);
            }
        }