Encoding & Decoding
Altruist provides a Codec system for serializing and deserializing packets. You can set a global codec and optionally override it per transport.
Available Codecs
| Codec | Config Value | Description |
|---|---|---|
| JSON | json | Human-readable, great for debugging and web clients |
| MessagePack | messagepack | Fast binary format. Smaller payloads, better performance |
Configuration
Global Codec
Set a default codec for all transports:
altruist:
server:
transport:
codec:
provider: messagepack
Per-Transport Codec Override
Different transports can use different codecs. Browser clients need JSON, while desktop clients benefit from MessagePack:
altruist:
server:
transport:
codec:
provider: messagepack # Global default
websocket:
enabled: true
path: /ws
codec:
provider: json # Override: browsers need JSON
tcp:
enabled: true
port: 13000
codec:
provider: messagepack # Override: binary for desktop
udp:
enabled: true
port: 13001
# No override: uses global (messagepack)
Note:
Per-transport codec overrides are optional. If a transport doesn't specify a codec section, it uses the global default. This lets you serve browser clients (JSON) and desktop clients (MessagePack) from the same server.
When to Use Which
| JSON | MessagePack | |
|---|---|---|
| Compatibility | Works with any web client | Requires MessagePack library on client |
| Speed | Moderate | Fast |
| Payload size | Larger | Compact |
| Debugging | Easy to read in logs | Binary, needs tooling |
| Best for | Web games, prototyping | Desktop/mobile games, production |
Note:
MessagePack is recommended for production game servers. It significantly reduces bandwidth and serialization overhead.
Annotating Packets for Both Codecs
Annotate your packets with both JSON and MessagePack attributes so they work with either codec:
[MessagePackObject]
public struct MovePacket : IPacketBase
{
[Key(0)]
public uint MessageCode { get; set; }
[Key(1)]
[JsonPropertyName("x")]
public float X { get; set; }
[Key(2)]
[JsonPropertyName("y")]
public float Y { get; set; }
}
This way your packet works regardless of which codec is configured — useful when running multiple transports with different codecs.
The ICodec Interface
public interface ICodec
{
IEncoder Encoder { get; }
IDecoder Decoder { get; }
}
public interface IEncoder
{
byte[] Encode<T>(T message);
byte[] Encode(object message, Type type);
}
public interface IDecoder
{
T Decode<T>(byte[] message);
T Decode<T>(byte[] message, Type type);
object Decode(byte[] message, Type type);
}
Creating a Custom Codec
If JSON and MessagePack don't fit your needs, implement ICodec. See Custom Codec for the full guide with Protobuf example.