> For the complete documentation index, see [llms.txt](https://kinematicsoup.gitbook.io/reactor/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kinematicsoup.gitbook.io/reactor/guides/matchmaking.md).

# Matchmaking

## Summary

Extends the lobby from [Tutorial 9](https://kinematicsoup.gitbook.io/reactor/tutorials/cluster_room_management.md) into a matchmaker for games with a fixed number of players per room. Before the lobby sends a player to a game room, it asks that room to hold a seat for them with a room-to-room RPC, and the room answers with a ticket the player connects with. The lobby fills the fullest game room first, starts game rooms only when players need them, and game rooms shut themselves down after they have been empty for a while.

Complete Tutorial 9 first. This page changes its 'ServerLobbyRoom', 'ServerGameRoom', 'ClientLobbyRoom', and 'Connect' scripts. It uses room-to-room RPCs, which [Tutorial 10](https://kinematicsoup.gitbook.io/reactor/tutorials/cluster_data_and_rpcs.md) introduces.

### Requirements

* [Reactor Requirements](https://kinematicsoup.gitbook.io/reactor/overview.md#requirements)
* Completion of [Tutorial 9](https://kinematicsoup.gitbook.io/reactor/tutorials/cluster_room_management.md).

## How It Works

In Tutorial 9, each game room writes its player count to its public data, and the lobby reads it from the `ksRoomInfo` list returned by `Cluster.GetRoomInfo("Game")`. That count is a snapshot from the lobby's last refresh, and a player the lobby sends to a room isn't counted until they finish connecting. If several players ask to join at once, or several lobbies share the game rooms, they can all be sent to the last free seat.

Only the game room knows how many players it really has, so the matchmaker lets it decide:

1. **The lobby picks a room** using public data, which is fine for choosing where to ask first.
2. **The lobby asks the room to hold a seat** with a `RESERVE_SEAT` room-to-room RPC.
3. **The game room checks its real count**: connected players plus seats it is already holding. It replies to the lobby with `SEAT_RESULT`, which carries a ticket if it has a seat or no ticket if it is full, and holds the seat for a few seconds.
4. **The lobby sends the player the room and the ticket.** The player connects to the game room with the ticket as a connect argument.
5. **The game room's authentication handler** lets in players with a valid ticket and turns everyone else away.

Room-to-room RPCs aren't confirmed, and an RPC to a room that is still starting or has stopped is dropped. The lobby handles that by giving up on a request that isn't answered in time and asking another room.

## Scripting

### Add Shared Constants

Add the cluster RPC ids, the room size, and the "no seat" authentication code to the constants script, so the lobby, game room, and client agree on them. Cluster RPCs have their own ids, separate from client RPC ids.

*Consts.cs*

```c#
// RPC IDs
public class RPC
{
    public const uint NUM_ROOMS = 0;
    public const uint JOIN_ROOM = 1;
    public const uint SHUT_DOWN = 2;
}

// Room-to-room RPC IDs used between the lobby and game rooms.
public class ClusterRPC
{
    public const uint RESERVE_SEAT = 0;
    public const uint SEAT_RESULT = 1;
    public const uint RELEASE_SEAT = 2;
}

public class Matchmaking
{
    // Maximum number of players in a game room.
    public const int MAX_PLAYERS = 6;

    // Authentication code a game room returns to a player without a valid ticket.
    public const uint NO_SEAT = 1;
}
```

### Modify the Server Game Room Script

The game room holds seats for players the lobby is sending, lets in players with a ticket, and shuts down after it has been empty for `EmptyTimeout` seconds. A new room starts with no players, so make the timeout long enough for the first player the lobby sends to arrive.

* A seat counts against the room's size from when it is reserved until its player joins, or until it expires if the player never arrives.
* Its public data reports connected players plus held seats, so the lobby's next refresh sees them.
* Authentication handlers must be registered in `Initialize`, and they can run off the main thread, so the seats are only used under a lock.
* Virtual players also go through authentication, and `ConnectedPlayerCount` doesn't include them, so the handler lets them through.

*ServerGameRoom.cs*

```c#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using KS.Reactor.Server;
using KS.Reactor;

public class ServerGameRoom : ksServerRoomScript
{
    // Seconds the room can be empty before it shuts down.
    [ksEditable] public float EmptyTimeout = 30f;

    // Seconds a seat is held for a player who hasn't joined yet.
    [ksEditable] public float SeatHoldTime = 10f;

    private class Seat
    {
        // Id of the player who authenticated with this seat's ticket, or 0 if no one has yet.
        public uint PlayerId;
        public float TimeLeft;
    }

    // Seats held for players the lobby is sending, keyed by ticket. Authentication handlers can run off the main
    // thread, so all access is under a lock.
    private Dictionary<uint, Seat> m_seats = new Dictionary<uint, Seat>();
    private Random m_random = new Random();
    private bool m_shuttingDown;
    private float m_emptyTime;

    // Called when the script is attached.
    public override void Initialize()
    {
        // Hide game rooms from clients' room lists; clients join through the lobby.
        Room.Info.IsPublic = false;
        Room.Info.PublicTags.Add("Game");

        Room.OnAuthenticate += Authenticate;
        Room.OnPlayerJoin += PlayerJoin;
        Room.OnPlayerLeave += PlayerLeave;
        Room.OnUpdate[0] += Update;
        UpdatePublicData();
    }

    // Called when the script is detached.
    public override void Detached()
    {
        Room.OnPlayerJoin -= PlayerJoin;
        Room.OnPlayerLeave -= PlayerLeave;
        Room.OnUpdate[0] -= Update;
    }

    // The lobby asks us to hold a seat. The first parameter of a cluster RPC handler is the id of the room that sent
    // it, which we use to reply. A ticket of 0 means there is no seat.
    [ksClusterRPC(ClusterRPC.RESERVE_SEAT)]
    private void ReserveSeat(uint lobbyRoomId, uint requestId)
    {
        uint ticket = 0;
        lock (m_seats)
        {
            if (!m_shuttingDown && Room.ConnectedPlayerCount + m_seats.Count < Matchmaking.MAX_PLAYERS)
            {
                do
                {
                    ticket = (uint)m_random.Next(1, int.MaxValue);
                }
                while (m_seats.ContainsKey(ticket));
                m_seats[ticket] = new Seat { TimeLeft = SeatHoldTime };
            }
        }
        UpdatePublicData();
        Cluster.CallRoomRPC(new uint[] { lobbyRoomId }, ClusterRPC.SEAT_RESULT, requestId, ticket);
    }

    // The lobby no longer needs a seat it reserved, because its player left or it stopped waiting for our answer.
    [ksClusterRPC(ClusterRPC.RELEASE_SEAT)]
    private void ReleaseSeat(uint lobbyRoomId, uint ticket)
    {
        lock (m_seats)
        {
            Seat seat;
            if (m_seats.TryGetValue(ticket, out seat) && seat.PlayerId == 0)
            {
                m_seats.Remove(ticket);
            }
        }
        UpdatePublicData();
    }

    // Lets in players whose first connect argument is a ticket for a seat we are holding. A non-zero code fails
    // authentication.
    private Task<ksAuthenticationResult> Authenticate(
        ksIServerPlayer player, ksMultiType[] args, CancellationToken cancellationToken)
    {
        if (player.IsVirtual)
        {
            return Task.FromResult(new ksAuthenticationResult(0));
        }
        uint ticket = args != null && args.Length > 0 ? args[0].UInt : 0;
        lock (m_seats)
        {
            Seat seat;
            if (ticket != 0 && m_seats.TryGetValue(ticket, out seat) && seat.PlayerId == 0)
            {
                // Keep the seat until the player joins, so it still counts against the room's size.
                seat.PlayerId = player.Id;
                seat.TimeLeft = SeatHoldTime;
                return Task.FromResult(new ksAuthenticationResult(0));
            }
        }
        return Task.FromResult(new ksAuthenticationResult(Matchmaking.NO_SEAT));
    }

    private void PlayerJoin(ksIServerPlayer player)
    {
        if (player.IsVirtual)
        {
            return;
        }
        // The player is in ConnectedPlayerCount now, so release their seat.
        lock (m_seats)
        {
            uint joinedTicket = 0;
            foreach (KeyValuePair<uint, Seat> pair in m_seats)
            {
                if (pair.Value.PlayerId == player.Id)
                {
                    joinedTicket = pair.Key;
                    break;
                }
            }
            m_seats.Remove(joinedTicket);
        }
        UpdatePublicData();
    }

    private void PlayerLeave(ksIServerPlayer player)
    {
        if (!player.IsVirtual)
        {
            UpdatePublicData();
        }
    }

    // Publishes connected players plus held seats for the lobby to read.
    private void UpdatePublicData()
    {
        lock (m_seats)
        {
            Room.Info.PublicData["players"] = Room.ConnectedPlayerCount + m_seats.Count;
        }
    }

    // Expires seats whose players never arrived, and shuts the room down once it has been empty for EmptyTimeout
    // seconds.
    private void Update()
    {
        bool expired = false;
        int seatCount;
        lock (m_seats)
        {
            List<uint> expiredTickets = new List<uint>();
            foreach (KeyValuePair<uint, Seat> pair in m_seats)
            {
                pair.Value.TimeLeft -= Time.RealDelta;
                if (pair.Value.TimeLeft <= 0f)
                {
                    expiredTickets.Add(pair.Key);
                }
            }
            foreach (uint ticket in expiredTickets)
            {
                m_seats.Remove(ticket);
                expired = true;
            }
            seatCount = m_seats.Count;
        }
        if (expired)
        {
            UpdatePublicData();
        }

        if (Room.ConnectedPlayerCount > 0 || seatCount > 0)
        {
            m_emptyTime = 0f;
            return;
        }
        m_emptyTime += Time.RealDelta;
        if (m_emptyTime >= EmptyTimeout)
        {
            ksLog.Info("Room has been empty for " + EmptyTimeout + " seconds. Shutting down.");
            lock (m_seats)
            {
                m_shuttingDown = true;
            }
            Room.ShutDown();
            Room.OnUpdate[0] -= Update;
        }
    }
}
```

`Room.ShutDown` doesn't stop the room immediately: the room keeps running for a few seconds after its last sync, and `Room.OnShutDown` fires as it stops. The room refuses new seats once it starts shutting down.

The tickets in this example stop players from taking a seat the lobby didn't give them, but `System.Random` numbers can be guessed. If players could gain from skipping the lobby, generate tickets with a cryptographic random number generator, or have the lobby pass something the game room can verify, as in [Authentication](https://kinematicsoup.gitbook.io/reactor/tutorials/authentication.md).

### Modify the Server Lobby Room Script

The lobby no longer keeps a target number of rooms. It queues players who ask to join, and each frame asks the fullest room that looks like it has space to hold a seat for the next queued player. When no room looks like it has space and no room is already starting, it starts one.

* Cluster request callbacks run off the main thread, so they only update the room list under a lock. Cluster RPC handlers run on the main thread by default, as do matching and RPCs.
* A room that refuses a seat, or doesn't answer in time, is skipped until the next refresh of the room list. A request can go unanswered because the room is still starting or has stopped, since room-to-room RPCs to those rooms are dropped.
* If a seat arrives after the lobby has stopped waiting for it, or after its player has left the lobby, the lobby tells the room to release it.
* A room started with `Cluster.StartRoom` is in `GetRoomInfo` results right away, with the tags and public data passed to `StartRoom`. The start request completes once the new room has connected to the cluster, and from then on it receives room-to-room RPCs.

*ServerLobbyRoom.cs*

```c#
using System.Collections.Generic;
using KS.Reactor.Server;
using KS.Reactor;

public class ServerLobbyRoom : ksServerRoomScript
{
    // How often to refresh the list of game rooms.
    [ksEditable] public float RefreshInterval = 2f;

    // Seconds to wait for a game room to answer a seat request.
    [ksEditable] public float SeatRequestTimeout = 4f;

    // A seat request sent to a game room, waiting for its answer.
    private class SeatRequest
    {
        public ksIServerPlayer Player;
        public ksRoomInfo Room;
        public float TimeLeft;
    }

    // Game rooms from the last refresh, and rooms skipped until the next refresh because they refused a seat or didn't
    // answer. Cluster request callbacks run off the main thread, so both are only used under a lock.
    private List<ksRoomInfo> m_rooms = new List<ksRoomInfo>();
    private HashSet<uint> m_skippedRooms = new HashSet<uint>();
    private object m_roomsLock = new object();
    private bool m_startingRoom;
    private int m_nextRoomNumber;
    private float m_refreshTimer;

    // Players waiting for a room, and seat requests waiting for an answer. Only used on the main thread.
    private List<ksIServerPlayer> m_waiting = new List<ksIServerPlayer>();
    private Dictionary<uint, SeatRequest> m_requests = new Dictionary<uint, SeatRequest>();
    private uint m_nextRequestId = 1;

    // Called when the script is attached.
    public override void Initialize()
    {
        Room.OnUpdate[0] += Update;
        Room.OnPlayerLeave += PlayerLeave;
    }

    // Called when the script is detached.
    public override void Detached()
    {
        Room.OnUpdate[0] -= Update;
        Room.OnPlayerLeave -= PlayerLeave;
    }

    // Clients call this RPC when they want to join a game room.
    [ksRPC(RPC.JOIN_ROOM)]
    private void OnRequestJoinRoom(ksIServerPlayer player)
    {
        if (m_waiting.Contains(player))
        {
            return;
        }
        foreach (SeatRequest request in m_requests.Values)
        {
            if (request.Player == player)
            {
                return;
            }
        }
        m_waiting.Add(player);
    }

    // A player who leaves while a seat is being requested for them is handled when the answer arrives.
    private void PlayerLeave(ksIServerPlayer player)
    {
        m_waiting.Remove(player);
    }

    // Called during the update cycle.
    private void Update()
    {
        // The room connects to the cluster after Initialize.
        if (!Cluster.IsConnected)
        {
            return;
        }

        // Refresh the room list.
        m_refreshTimer -= Time.RealDelta;
        if (m_refreshTimer <= 0f)
        {
            m_refreshTimer = RefreshInterval;
            Cluster.GetRoomInfo("Game").OnComplete = OnGetRooms;
        }

        CheckSeatRequestTimeouts();
        MatchWaitingPlayers();
    }

    // Asks a room for a seat for each waiting player, and starts a room if none looks like it has space.
    private void MatchWaitingPlayers()
    {
        lock (m_roomsLock)
        {
            while (m_waiting.Count > 0)
            {
                ksRoomInfo room = FindRoom();
                if (room == null)
                {
                    StartGameRoom();
                    return;
                }
                ksIServerPlayer player = m_waiting[0];
                m_waiting.RemoveAt(0);

                uint requestId = m_nextRequestId++;
                m_requests[requestId] = new SeatRequest { Player = player, Room = room, TimeLeft = SeatRequestTimeout };
                Cluster.CallRoomRPC(new uint[] { room.Id }, ClusterRPC.RESERVE_SEAT, requestId);
            }
        }
    }

    // A game room answered a seat request. A ticket of 0 means the room is full.
    [ksClusterRPC(ClusterRPC.SEAT_RESULT)]
    private void SeatResult(uint gameRoomId, uint requestId, uint ticket)
    {
        SeatRequest request;
        if (!m_requests.TryGetValue(requestId, out request))
        {
            // We stopped waiting for this answer. If the room held a seat anyway, let it go.
            ReleaseSeat(gameRoomId, ticket);
            return;
        }
        m_requests.Remove(requestId);

        if (!request.Player.IsConnected)
        {
            ReleaseSeat(gameRoomId, ticket);
        }
        else if (ticket == 0)
        {
            // The room is full. Skip it until the next refresh and find the player another room.
            lock (m_roomsLock)
            {
                m_skippedRooms.Add(gameRoomId);
            }
            m_waiting.Insert(0, request.Player);
        }
        else
        {
            Room.CallRPC(request.Player, RPC.JOIN_ROOM, request.Room, ticket);
        }
    }

    private void ReleaseSeat(uint gameRoomId, uint ticket)
    {
        if (ticket != 0)
        {
            Cluster.CallRoomRPC(new uint[] { gameRoomId }, ClusterRPC.RELEASE_SEAT, ticket);
        }
    }

    // Gives up on seat requests that weren't answered in time, and queues their players again.
    private void CheckSeatRequestTimeouts()
    {
        List<uint> expired = new List<uint>();
        foreach (KeyValuePair<uint, SeatRequest> pair in m_requests)
        {
            pair.Value.TimeLeft -= Time.RealDelta;
            if (pair.Value.TimeLeft <= 0f)
            {
                expired.Add(pair.Key);
            }
        }
        foreach (uint requestId in expired)
        {
            SeatRequest request = m_requests[requestId];
            m_requests.Remove(requestId);
            ksLog.Warning("Game room " + request.Room.Id + " didn't answer a seat request.");
            lock (m_roomsLock)
            {
                m_skippedRooms.Add(request.Room.Id);
            }
            if (request.Player.IsConnected)
            {
                m_waiting.Insert(0, request.Player);
            }
        }
    }

    // Returns the room with the most players that looks like it has space, or null if none does.
    private ksRoomInfo FindRoom()
    {
        ksRoomInfo best = null;
        int bestCount = -1;
        foreach (ksRoomInfo room in m_rooms)
        {
            if (m_skippedRooms.Contains(room.Id))
            {
                continue;
            }
            int count = GetPlayerCount(room);
            if (count < Matchmaking.MAX_PLAYERS && count > bestCount)
            {
                best = room;
                bestCount = count;
            }
        }
        return best;
    }

    // Players and seats the room last reported, plus seats we have asked it for since. This only decides which room to
    // ask; the room decides whether it has a seat.
    private int GetPlayerCount(ksRoomInfo room)
    {
        // GetField with a default returns null if the room hasn't published a count; null converts to 0.
        int count = room.PublicData.GetField("players", null);
        foreach (SeatRequest request in m_requests.Values)
        {
            if (request.Room.Id == room.Id)
            {
                count++;
            }
        }
        return count;
    }

    private void StartGameRoom()
    {
        if (m_startingRoom)
        {
            return;
        }
        m_startingRoom = true;
        ksJSON publicData = new ksJSON();
        publicData["players"] = 0;
        Cluster.StartRoom("Game" + m_nextRoomNumber++, "ClusterTutorial", "GameRoom", publicData, "Game")
            .OnComplete = OnStartRoom;
    }

    // Called off the main thread when the GetRoomInfo request completes.
    private void OnGetRooms(ksAsyncResult<List<ksRoomInfo>> result)
    {
        if (!string.IsNullOrEmpty(result.Error))
        {
            ksLog.Error("Error getting rooms: " + result.Error);
            return;
        }
        lock (m_roomsLock)
        {
            m_rooms = result.Result;
            m_skippedRooms.Clear();
        }
    }

    // Called off the main thread when the StartRoom request completes.
    private void OnStartRoom(ksAsyncResult<ksRoomInfo> result)
    {
        lock (m_roomsLock)
        {
            m_startingRoom = false;
            if (!string.IsNullOrEmpty(result.Error))
            {
                ksLog.Error("Error starting room: " + result.Error);
                return;
            }
            // Add the room now rather than waiting for the next refresh. It is connected to the cluster, so it can
            // answer seat requests.
            m_rooms.Add(result.Result);
            m_skippedRooms.Remove(result.Result.Id);
        }
    }
}
```

### Modify the Client Lobby Room Script

The lobby now sends a ticket along with the room. Remove the code that sets the number of game rooms, since the lobby no longer uses it, and pass the ticket to the connect script.

*ClientLobbyRoom.cs*

```c#
using UnityEngine;
using KS.Reactor.Client.Unity;
using KS.Reactor;

public class ClientLobbyRoom : ksRoomScript
{
    // Called every frame.
    private void Update()
    {
        // When J is pressed, call an RPC to request a game room to join.
        if (Input.GetKeyDown(KeyCode.J))
        {
            Room.CallRPC(RPC.JOIN_ROOM);
        }
    }

    // The server calls this RPC with the game room to join and the ticket for the seat it is holding.
    [ksRPC(RPC.JOIN_ROOM)]
    private void JoinRoom(ksMultiType[] args)
    {
        if (args.Length == 2 && Connect.Instance != null)
        {
            Connect.Instance.ConnectToServer(args[0].ToSerializable<ksRoomInfo>(), args[1].UInt);
        }
    }
}
```

### Modify the Connect Script

`ConnectToServer` takes connect arguments to pass to `Connect`, which the game room's authentication handler receives as `args`. Change its signature and the `room.Connect()` call at its end:

*Connect.cs*

```c#
    // Connect to a server whose location is described in a ksRoomInfo object, passing connect arguments to its
    // authentication handlers.
    public void ConnectToServer(ksRoomInfo roomInfo, params ksMultiType[] connectArgs)
    {
        // ... the rest of the function is unchanged, except the last line:
        room.Connect(connectArgs);
    }
```

When the game room turns a player away, the client gets the connect status `AUTH_ERR_USER_DEFINED` with the room's code in `result.Code`. This happens if the seat expired before the player arrived. A failed connection doesn't fire `OnDisconnect`, so handle it in the connect handler by going back to the lobby:

*Connect.cs*

```c#
    // Handle a ksRoom connect event.
    private void HandleConnect(ksRoom.ConnectStatus status, ksAuthenticationResult result)
    {
        if (status == ksRoom.ConnectStatus.SUCCESS)
        {
            ksLog.Info("Connected to " + m_room);
        }
        else if (status == ksRoom.ConnectStatus.AUTH_ERR_USER_DEFINED && result.Code == Matchmaking.NO_SEAT)
        {
            // Our seat is gone. Return to the lobby, where we can ask for another room.
            ksLog.Info(m_room + " has no seat for us. Returning to the lobby.");
            m_room = null;
            ConnectToServer();
        }
        else
        {
            ksLog.Error("Unable to connect to " + m_room + " (" + status + ", " + result + ")");
        }
    }
```

## Testing

Test with the local cluster as in [Tutorial 9](https://kinematicsoup.gitbook.io/reactor/tutorials/cluster_room_management.md#local-cluster). To see rooms fill, set `MAX_PLAYERS` to 2 and run several clients (for example, a build and the editor).

1. Build your scene config (**CTRL + F2**) and launch the local cluster.
2. Connect a client to the lobby and press **J**. The lobby starts a game room, the room holds a seat, and you join it. The game room's logs show the seat request.
3. Connect a second client and press **J**. It joins the same room, because that room is the fullest with space.
4. Connect a third client and press **J**. The room is full, so the lobby starts a second room.
5. Disconnect every client from a room and wait `EmptyTimeout` seconds. The room shuts itself down.
