Game Session Portal

The AltruistGameSessionPortal provides built-in game session management — handling player connections, room assignments, handshakes, and disconnections out of the box.

Overview

AltruistGameSessionPortal extends Portal and implements OnConnectedAsync and OnDisconnectedAsync. It provides three built-in gates:

GateEventDescription
HandshakeAsynchandshakeReturns server info and room data to the client
JoinGameAsyncjoin-gameAdds a player to a game session/room
ExitGameAsyncleave-gameRemoves a player from the session

Usage

Extend the portal and add it to your project:

[Portal("/game")]
public class MyGamePortal : AltruistGameSessionPortal
{
    public MyGamePortal(
        IGameSessionService gameSessionService,
        IAltruistRouter router)
        : base(gameSessionService, router)
    {
    }
}

The three gates are automatically available — no additional code needed.

Customizing Behavior

Override the hook methods to customize each flow:

[Portal("/game")]
public class MyGamePortal : AltruistGameSessionPortal
{
    public MyGamePortal(IGameSessionService gameSessionService, IAltruistRouter router)
        : base(gameSessionService, router) { }

    protected override async Task<IResultPacket> OnHandshakeReceived(
        HandshakeRequestPacket message, string clientId, IResultPacket result)
    {
        // Modify or extend the handshake result
        return result;
    }

    protected override async Task<IResultPacket> OnJoinGameReceived(
        JoinGamePacket message, string clientId, IResultPacket result)
    {
        // Custom join logic (e.g., validate player name)
        return result;
    }

    protected override async Task<RoomBroadcast?> OnExitGameReceived(
        LeaveGamePacket message, string clientId, RoomBroadcast? result)
    {
        // Custom leave logic (e.g., save player state)
        return result;
    }

    public override async Task OnDisconnectedAsync(string clientId, Exception? exception)
    {
        // Custom disconnect handling
        await base.OnDisconnectedAsync(clientId, exception);
    }
}

Client Events

Join Game

{
  "messageCode": 4,
  "event": "join-game",
  "name": "Player1",
  "roomId": null,
  "world": 0,
  "position": [0, 0]
}

Leave Game

{
  "messageCode": 4,
  "event": "leave-game",
  "clientId": "player-connection-id"
}

Handshake

{
  "messageCode": 4,
  "event": "handshake"
}

Room Management

The GameSessionService automatically manages rooms:

  • Players are assigned to rooms on join
  • When a room reaches capacity, a new room is created automatically
  • Rooms are cleaned up when empty
  • Session cleanup runs periodically