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
| Component | Property | Description |
|---|---|---|
| ClientSender | Client | Send to a specific client by ID |
| RoomSender | Room | Send to all clients in a room |
| BroadcastSender | Broadcast | Send to all connected clients |
| ClientSynchronizator | Synchronize | Sync 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:
- Your
IPacketBasepacket is wrapped in aMessageEnvelopewith aPacketHeader(sender, receiver, timestamp) - The envelope is encoded using the configured codec (JSON or MessagePack)
- 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!"
}
}