category: Application fundamentals
Stormancer natively includes an object serializer that uses MsgPack to transmit complex objects on the network in a cross platform way.
This binary serializer is quite effective at reducing message size, but no generic system can be as effective as custom made serialization. This is the reason why when you need to send data on the wire, you can choose either to:
- Use a writer function to write to the binary stream that will be sent as the message body. Nothing forbid you to use the serializer while writing the message content, for instance if you want to send several objects in a single message.
- Use the generic Send method to provide an object that will be serialized using MsgPack.
On the other side of the wire, the framework provides a ReadObject
Choosing between serialization and custom message crafting
Crafting a custom message is certainly the most effective way to optimize bandwidth and CPU consumption. Therefore you should definitely prefer it for simple messages that you expect to send often, for instance player position updates.
However, serialization automates message writing and provides many advantages:
- Automatic encoding of strings in UTF8
- Management of endianness
- Cross-platform serialization and deserialization
- Automatic serialization of complex object graphs
- Resilience to changes : Adding or removing object properties doesn't require changes to the message writing logic
- Performance hit, especially on Unity for iOS devices where we can't use dynamic compilation
- Serialized objects must be public classes or value type (in .NET)
- Bandwidth overhead (depends on what is serialized and the platform, see below for more)
Cross platform serialization
Different platforms may handle objects differently. For instance, .NET provides a lot of static metadata that can be used to optimize serialization and reduce message size: The .NET serializer omits property names and encodes objects as Arrays instead of maps.