0
I’m trying to use serialization to transfer data between Server and Client. However, I am having trouble trying to deserialize a class that has a type List of another class, when the class to be deserialized has no such list there is no error.
Error:
Function to serialize:
private static void Serialize(NetOutgoingMessage Data, object Element)
{
// Serializa os dados
MemoryStream Stream = new MemoryStream();
new BinaryFormatter().Serialize(Stream, Element);
Data.Write(Stream.GetBuffer().Length);
Data.Write(Stream.GetBuffer());
Stream.Close();
}
Function to deserialize:
private static object Deserialize(NetIncomingMessage Data)
{
// Deserializa os dados
BinaryFormatter Formater = new BinaryFormatter();
Formater.Binder = new Program.Binder();
return Formater.Deserialize(new MemoryStream(Data.ReadBytes(Data.ReadInt32())));
}
Binder:
public class Binder : System.Runtime.Serialization.SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
assemblyName = assemblyName.Replace("Client", "Server");
return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
}
}
Classes to be serialized:
[Serializable]
public class NPC
{
public string Name;
public string SayMsg;
public short Texture;
public byte Behaviour;
public byte SpawnTime;
public byte Sight;
public int Experience;
public short[] Vital;
public short[] Attribute;
public List<NPC_Drop> Drop;
public bool AttackNPC;
public List<short> Allie;
public byte Movement;
public byte Flee_Helth;
}
[Serializable]
public class NPC_Drop
{
public short Item_Num;
public short Amount;
public byte Chance;
}
How I send the data:
public static void Write_NPCs()
{
NetOutgoingMessage Data = Socket.Device.CreateMessage();
// Envia os dados
Data.Write((byte)Packets.Write_NPCs);
Serialize(Data, Lists.NPC);
Packet(Data);
}
How I get:
private static void Write_NPCs(byte Index, NetIncomingMessage Data)
{
// Lê e salva os dados
Lists.NPC = (Lists.Structures.NPC[])Deserialize(Data);
Write.NPCs();
}
Weird code, because you’re doing it like this, because you don’t use a guy to do it for you?
– novic
What do you mean, a guy? @Virgilionovic
– Ricardo Dalarme
There is already a package that does this !!! because it is doing so so?
– novic
Complementing what Virgilio commented, I will do a free jabá here but it is usually used newtonsoft json, including found in git of . net a very constructive conversation about the use of binaryformatter being deprecated https://github.com/dotnet/runtime/issues/23341#issuecomment-325826116
– Lucas Miranda