Altruist Router

The IAltruistRouter is the primary way to send packets from the server to clients. It provides four routing components for different communication patterns.

Router Components

ComponentPropertyDescription
ClientSenderClientSend to a specific client by ID
RoomSenderRoomSend to all clients in a room
BroadcastSenderBroadcastSend to all connected clients
ClientSynchronizatorSynchronizeSync entity state to clients
Loading diagram...

Injecting the Router

Inject IAltruistRouter via constructor in any portal or service:

[Portal("/game")]
public class MyPortal : Portal
{
    private readonly IAltruistRouter _router;

    public MyPortal(IAltruistRouter router)
    {
        _router = router;
    }
}

Sending to a Specific Client

await _router.Client.SendAsync(clientId, new ChatPacket("Hello!"));

The ClientSender looks up the connection by ID and sends the encoded packet directly.

Sending to a Room

await _router.Room.SendAsync(roomId, new GameStatePacket { ... });

The RoomSender retrieves all connections in the room and sends the packet to each one.

Broadcasting to All Clients

// Send to everyone
await _router.Broadcast.SendAsync(new ServerAnnouncement("Maintenance in 5 minutes"));

// Send to everyone except one client
await _router.Broadcast.SendAsync(packet, excludeClientId: senderId);

Entity Synchronization

The Synchronize component enables efficient delta-based synchronization of entities:

await _router.Synchronize.SendAsync(playerEntity);

This detects changed properties (via [Synced] attributes) and sends only the delta to connected clients. See Entity Synchronization for details.

How Packets Are Sent

When you call any SendAsync method:

  1. Your IPacketBase packet is wrapped in a MessageEnvelope with a PacketHeader (sender, receiver, timestamp)
  2. The envelope is encoded using the configured codec (JSON or MessagePack)
  3. The raw bytes are sent through the transport connection (WebSocket, TCP, or UDP)

This means clients always receive:

{
  "messageCode": 1000,
  "header": {
    "timestamp": 638790123456789,
    "receiver": "client-id-here",
    "sender": "server"
  },
  "message": {
    "text": "Hello!"
  }
}