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

CodecConfig ValueDescription
JSONjsonHuman-readable, great for debugging and web clients
MessagePackmessagepackFast 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)
Loading diagram...

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

JSONMessagePack
CompatibilityWorks with any web clientRequires MessagePack library on client
SpeedModerateFast
Payload sizeLargerCompact
DebuggingEasy to read in logsBinary, needs tooling
Best forWeb games, prototypingDesktop/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.