Home > OS >  The serialized object result of my unit client is different from that of the c# console server
The serialized object result of my unit client is different from that of the c# console server

Time:01-16

same class for serialize:

using System;
[Serializable]
class Class2
{
    public int a;
}

same serialize function:

        public static byte[] Serialize(object obj)
        {
            if (obj == null || !obj.GetType().IsSerializable)
            {
                return null;
            }

            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, obj);
                byte[] data = stream.ToArray();
                return data;
            }
        }

sever:

Class2 c = new Class2();
c.a = 1 ;
byte[] data = NetworkUtils.Serialize(c);
Console.WriteLine( BitConverter.ToString(data));

unity client:

Class2 c = new Class2();
c.a = 1;
byte[] data = NetworkUtils.Serialize(c);
Debug.Log("测试序列化 "   BitConverter.ToString(data));

is this problem about .net edition? unity is standard2,server is core3.1

unity result: 00-01-00-00-00-FF-FF-FF-FF-01-00-00-00-00-00-00-00-0C-02-00-00-00-46-41-73-73-65-6D-62-6C-79-2D-43-53-68-61-72-70-2C-20-56-65-72-73-69-6F-6E-3D-30-2E-30-2E-30-2E-30-2C-20-43-75-6C-74-75-72-65-3D-6E-65-75-74-72-61-6C-2C-20-50-75-62-6C-69-63-4B-65-79-54-6F-6B-65-6E-3D-6E-75-6C-6C-05-01-00-00-00-06-43-6C-61-73-73-32-01-00-00-00-01-61-00-08-02-00-00-00-01-00-00-00-0B UnityEngine.Debug:Log (object)

server result: 00-01-00-00-00-FF-FF-FF-FF-01-00-00-00-00-00-00-00-0C-02-00-00-00-3B-47-61-6D-65-2C-20-56-65-72-73-69-6F-6E-3D-31-2E-30-2E-30-2E-30-2C-20-43-75-6C-74-75-72-65-3D-6E-65-75-74-72-61-6C-2C-20-50-75-62-6C-69-63-4B-65-79-54-6F-6B-65-6E-3D-6E-75-6C-6C-05-01-00-00-00-06-43-6C-61-73-73-32-01-00-00-00-01-61-00-08-02-00-00-00-01-00-00-00-0B

PS:If I make the class into a DLL file and import it, this problem will not appear,But this method is too troublesome

CodePudding user response:

If you compare the strings what you get is on your server

FAssembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Class2 a

And in Unity

Game, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Class2 a

(I left out the not printable Chars) The difference is the Assembly name. In Unity it is Game, on your server it is FAssembly.


In general as said STOP using BinaryFormatter at all!!

Despite the security concerns it is also a huge waste of bandwidth!

In Unity you send 111 and on the server even 122 bytes!

Your class has a single int field which only requires 4 bytes of data!

As said I would rather implement

[Serializable]
class Class2
{
    public int a;

    public byte[] ToBytes()
    {
        return BitConverter.GetBytes(a);
    }

    public Class2(){}

    public Class2(byte[] bytes)
    {
        a = BitConverter.ToInt32(bytes);
    }
}
  •  Tags:  
  • Related