Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - More efficient serialization for packets

I'm creating a program which has to send data between a client and server efficiently. To organize packets clearly, I'm using serialization. However, when I serialize these packets the data is unnecessarily large. I'll explain what I'm doing so that you can understand what I need.

My packet classes work like this. I have a Packet object:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Packet
{
    public static byte[] Serialize(Object o)
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, o);
        return ms.ToArray();
    }

    public static Object Deserialize(byte[] bt)
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();

        ms.Write(bt, 0, bt.Length);
        ms.Position = 0;

        object obj = bf.Deserialize(ms);

        ms.Close();

        return obj;
    }
}

I can then create other classes that inherit from the Packet class, here's an example:

using System;

[Serializable]
public class PacketUserInfo : Packet
{
    public string Name;
    public int Age;
}

Then, it's very simple to put this into a byte array and send it (Of course the above packet is merely an example). However, the size of the resulting array is at least 10 times larger than it would be if I was to use a BinaryWriter and manually write the information.

Why is the serialized data so large? Is there any way to decrease it while still keeping everything organized with packets as their own classes?

Note: I'm only intending to serialize simple properties like this, nothing fancy.

like image 801
Jordan Avatar asked May 25 '26 14:05

Jordan


1 Answers

Where you say "Why is the serialized data [...] larger than it would be if I was to use a BinaryWriter and manually write the information", with information you mean property values. The serializer you use however, serializes not only the data, but also some information about the class. You can see this by viewing the serialized data in a text editor.

Is there any way to decrease it while still keeping everything organized with packets as their own classes?

Use more specialized serialization, like protobuf or the library suggested by @Piotr.

Also I think your serialization code should not reside in the Packet base class, but rather in a separate class, like PacketEncoder.

like image 120
CodeCaster Avatar answered May 28 '26 05:05

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!