MultiConnectMultiConnectDocs Website home
MultiConnectSDK › Developer Guide

9. Server Reference

Choosing a shape

Your rooms are the same code in every shape, so you can start small and grow.

Shape What it is Good for
Combined One server does matchmaking and gameplay. Run more of them, in more regions, as you grow Most games, and the place to start
Master and game servers Masters match players; game servers run the matches A busy lobby, or gameplay that needs far more CPU than matchmaking

You choose the shape when you create a deployment: Combined or Master–Worker on the dashboard.

Your rooms

A room is a class with IRoom. It is the same on MultiConnectCloud and on your own servers:

This script uses your own message types, such as GameMessage. Define yours in one shared file, as in Script 2.1 and Script 7.6.

Script 9.1: DefaultGameRoom.cs

using System.Collections.Generic;
using MultiConnect.Global;
using MultiConnect.Serialization;
using MultiConnect.Server;
using MultiConnect;
using UnityEngine;

public class DefaultGameRoom : IRoom
{
    private Room room;
    private List<string> connectedPlayers = new List<string>();
    
    public void OnRoomCreated(Room room)
    {
        this.room = room;
        Debug.Log($"[Room {room.roomId}] Created");
        
        // Setup message listeners
        room.AddResponseListener(GameMessage.PlayerMove, OnPlayerMove);
        room.AddResponseListener(GameMessage.ChatMessage, OnChatMessage);
        
        // Subscribe to spectator events
        room.onSpectatorJoined += OnSpectatorJoined;
        room.onSpectatorleft += OnSpectatorLeft;
    }
    
    public void OnRoomJoined(string playerId, string playerData = "")
    {
        Debug.Log($"[Room {room.roomId}] Player joined: {playerId}");
        connectedPlayers.Add(playerId);
        
        // Notify all players about new player
        var joinData = new PlayerJoinedData
        {
            playerId = playerId,
            playerData = playerData
        };
        room.SendMcBinaryToAll(joinData, GameMessage.PlayerJoined, McProtocol.Reliable);
        
        // Check if game should start
        if (connectedPlayers.Count >= room.players.Count)
        {
            StartGame();
        }
    }
    
    public void OnLeaveRoom(string playerId, string msg = "")
    {
        Debug.Log($"[Room {room.roomId}] Player left: {playerId}, Reason: {msg}");
        connectedPlayers.Remove(playerId);
        
        // Notify remaining players
        var leftData = new PlayerLeftData
        {
            playerId = playerId,
            reason = msg
        };
        room.SendMcBinaryToAll(leftData, GameMessage.PlayerLeft, McProtocol.Reliable);
    }
    
    public void OnRejoinRoom(string playerId)
    {
        Debug.Log($"[Room {room.roomId}] Player rejoined: {playerId}");
        
        // Send current game state to rejoining player
        // SendGameState(playerId);
    }
    
    public void OnPlayerDisconnected(string playerId)
    {
        Debug.Log($"[Room {room.roomId}] Player disconnected: {playerId}");
        // Player may reconnect within removePlayerTime
    }
    
    public void OnDestroyRoom()
    {
        Debug.Log($"[Room {room.roomId}] Destroyed");
        room.RemoveAllListener();
        connectedPlayers.Clear();
    }
    
    // ═══════════════════════════════════════════════════════════
    // GAME LOGIC
    // ═══════════════════════════════════════════════════════════
    
    void StartGame()
    {
        Debug.Log($"[Room {room.roomId}] Starting game!");
        
        // Close room to prevent new players
        room.isOpen = false;
        
        // Notify all players
        var startData = new GameStartData { timestamp = System.DateTime.UtcNow };
        room.SendMcBinaryToAll(startData, GameMessage.GameStart, McProtocol.Reliable);
    }
    
    void OnPlayerMove(object obj)
    {
        var moveData = (PlayerMoveData)obj;
        
        // Validate movement (anti-cheat)
        if (!ValidateMove(moveData))
        {
            Debug.LogWarning($"Invalid move from {moveData.playerId}");
            return;
        }
        
        // Broadcast to all other players
        room.SendMcBinaryToAll(moveData, GameMessage.PlayerMove, McProtocol.Unreliable);
    }
    
    void OnChatMessage(object obj)
    {
        var chatData = (ChatMessageData)obj;
        
        // Broadcast to all players
        room.SendMcBinaryToAll(chatData, GameMessage.ChatMessage, McProtocol.Reliable);
    }
    
    void OnSpectatorJoined(string spectatorId)
    {
        Debug.Log($"[Room {room.roomId}] Spectator joined: {spectatorId}");
    }
    
    void OnSpectatorLeft(string spectatorId)
    {
        Debug.Log($"[Room {room.roomId}] Spectator left: {spectatorId}");
    }
    
    bool ValidateMove(PlayerMoveData data)
    {
        // Add your validation logic here
        return true;
    }
}

[McSerializationObject]
public class GameStartData
{
    public System.DateTime timestamp;
}

Combined server

On MultiConnectCloud

Add MultiConnectGameServer to your server scene:

Field Value
Sdk Key Your key
Use Custom Hosting Off
Use As Master Server On
Hosted Max Players The most players one server takes
Local Port Where it listens when you test on your machine

Then add Script 9.2 to tell it how to make rooms. That is all the server code it needs:

Script 9.2: ServerBootstrap.cs

using UnityEngine;
using MultiConnect.Server;
using System.Collections.Generic;

public class ServerBootstrap : MonoBehaviour, IRoomController
{
    void Awake() => MatchMaking.SetRoomController(this);

    public IRoom GetRoom(Dictionary<string, string> parameters)
    {
        // Choose a room class from what the client asked for in FindRoom.
        return parameters.TryGetValue("gameMode", out var mode) && mode == "deathmatch"
            ? new DeathmatchRoom()
            : (IRoom)new DefaultGameRoom();
    }

    public IRoom GetRoom(string parameterClass) => new DefaultGameRoom();
}

Deploy it with Build and Deploy. The platform starts as many servers as you set for each region, gives each its port, and restarts one that stops.

On your own servers

Add the same component and the same room code, and tick Use Custom Hosting. You then start the server yourself, and watch over it:

Script 9.3: OwnCombinedServer.cs

using UnityEngine;
using MultiConnect;
using MultiConnect.Server;
using MultiConnect.Unity;

public class OwnCombinedServer : MonoBehaviour
{
    [SerializeField] private int serverPort = 7777;
    [SerializeField] private int maxPlayers = 2000;

    void Start()
    {
        if (MultiConnectInfo.IsMultiConnectInitialized()) StartServer();
        else MultiConnectInfo.onMultiConnectInitialized += StartServer;
    }

    void StartServer()
    {
        GameServer.onServerStarted += () => Debug.Log("Server started");
        GameServer.onSocketAdded += playerId => Debug.Log("Player connected: " + playerId);
        GameServer.onSocketRemove += playerId => Debug.Log("Player disconnected: " + playerId);

        // Use your server's public address: the health monitor connects to it.
        GameServer.SetMonitorServerUrl("ws://YOUR_SERVER_ADDRESS:" + serverPort);
        MultiConnectGameServer.instance.StartServer(serverPort, maxPlayers);
    }
}

Also yours to run: a Linux machine, the open port, a certificate for wss://, restarting the process if it stops, copying each new build across, and deciding when players move to it.

Master and game servers

Two scenes make two builds, usually in one Unity project:

Clients only ever connect to the master. When it places a player in a room, MultiConnectSDK moves that player to the right game server and raises GameRooms.OnRoomJoined. Your client code does not change.

The dashboard and the Build and Deploy Server window call game servers workers. They are the same thing.

On MultiConnectCloud

Component fields:

Field Value
Sdk Key Your key, on both scenes
Use Custom Hosting Off, on both scenes
Hosted Max Players The most players one server takes
Local Port Where it listens on your machine. Give the two scenes different ports

To create the deployment:

  1. In File > Build Profiles, enable the master scene and the game server scene.
  2. Open MultiConnect > Build and Deploy Server. Under New deployment? Make its first build, tick Master + game servers, tick each scene under Master or Worker, and press Build First Zip. You get two zips, ending -master.zip and -worker.zip.
  3. On the dashboard, create a Server deployment as in Create your server deployment, with Mode set to Master–Worker. Choose how its game servers run, and upload each zip to Master build and Worker build.

To update it, press Build and Deploy in the same window. Both builds go out together.

The master finds its game servers by itself. There is no key to add, no script to write and no address list to keep.

To test on your machine:

  1. Set Local Port to 7777 on the master and 7778 on the game server, and keep Use Web Socket the same on both.
  2. Under Game Server Instances on the master, add one entry with IP 127.0.0.1 and Port 7778. Its other fields can stay empty. A deployed master does not use this list.
  3. On MultiConnectClient, turn on Connect To Local Server and set Local Server Address to 127.0.0.1:7777.
  4. Start the game server, then the master, then the client. Unity opens a project in one Editor at a time, so run at most one of them in the Editor and the rest as Development Builds.

Choosing how game servers run:

Always ready On demand
Runs A pool in each region, between the minimum and maximum you set One server per match, up to the most you allow at once
A player waits for Nothing, while a server has room The server to start, the first time
You pay for The pool, while it runs Each server, only while its match runs
Good for Matches starting all the time Matches that come and go, long matches, private matches

You choose when you create the deployment, and it stays that way.

Always ready
On demand

When players ask for a room, the master starts a game server and holds them until it is ready. Everyone who arrives in the meantime joins the same match, and a second server starts only when the first is full. On the dashboard you set the most that may run at once, and the longest one may run.

Two lines in your room finish the job:

Script 9.4

// When the match starts, so nobody joins late:
room.isOpen = false;

// When the match is over:
room.DestroyRoom();

The server exits 15 seconds after its last room ends, and billing for it stops. If it has more to do after that, such as saving results, turn this off and exit when you are done:

Script 9.5

McHostedServer.ExitWhenMatchEnds = false;
On demand, started from your code

To decide yourself when servers run, for a tournament or a scheduled event, turn off the one-per-match behaviour before the master starts. Servers you start accept rooms like any other, and keep running when empty until you stop them. Each new room goes to the ready server with the fewest rooms.

Script 9.6: TournamentServers.cs

using System.Threading.Tasks;
using UnityEngine;
using MultiConnect;

public class TournamentServers : MonoBehaviour
{
    private McInstance server;

    void Awake() => McHostedMaster.ManageGameServersInCode = true;

    public async Task OpenTournament()
    {
        // Using the same name again returns the same server, so a retry never starts a second.
        server = await McHostedMaster.StartGameServerAsync("tournament-1");
    }

    public async Task CloseTournament()
    {
        await McHostedMaster.StopGameServerAsync(server.InstanceId);
    }
}

To do the same from your own backend, open Access Keys on the dashboard, create a key with Manage instances on, and attach it to the deployment on its page. In .NET, McHostingClient has CreateInstanceAsync, ListInstancesAsync and RemoveInstanceAsync.

On your own servers

Tick Use Custom Hosting on both scenes, and add each game server's address to Game Server Instances on the master:

Field Description
Name A label for this game server
IP, Port Where the master and players reach it
Ws URL Its WebSocket address, if it listens for WebSocket
Protocols Reliable, plus Unreliable if it uses UDP

Then start each one from code:

Script 9.7: OwnMasterServer.cs

using MultiConnect.Server;
using MultiConnect.Shared;
using MultiConnect.Unity;
using MultiConnect;
using UnityEngine;

public class OwnMasterServer : MonoBehaviour
{
    [SerializeField] private int masterPort = 8888;
    [SerializeField] private int maxConnections = 10000;

    void Start()
    {
        if (MultiConnectInfo.IsMultiConnectInitialized()) StartServer();
        else MultiConnectInfo.onMultiConnectInitialized += StartServer;
    }

    void StartServer()
    {
        MasterServer.SetMonitorServerUrl("ws://YOUR_MASTER_ADDRESS:" + masterPort);
        MultiConnectMasterServer.instance.StartServer(masterPort, maxConnections);
    }

    // Call this whenever you add a game server or take one away.
    public void AddGameServer(string ip, int port, string wsUrl)
    {
        MultiConnectMasterServer.instance.gamerServerInstances.Add(new GameServerInfo
        {
            IP = ip,
            Port = port,
            WsURL = wsUrl
        });
        MultiConnectMasterServer.instance.UpdateGameServerConnections();
    }
}

public class OwnGameServer : MonoBehaviour
{
    [SerializeField] private int serverPort = 7777;
    [SerializeField] private int maxPlayers = 500;

    void Start()
    {
        if (MultiConnectInfo.IsMultiConnectInitialized()) StartServer();
        else MultiConnectInfo.onMultiConnectInitialized += StartServer;
    }

    void StartServer()
    {
        GameServer.SetMonitorServerUrl("ws://YOUR_SERVER_ADDRESS:" + serverPort);
        MultiConnectGameServer.instance.StartServer(serverPort, maxPlayers);
    }
}

Also yours to run: the machines for every master and game server, keeping that address list current as servers come and go, and draining a server by hand before you update or remove it.

Side by side

MultiConnectCloud Your own servers
Starting servers Done for you Your code and your machines
Ports and addresses Assigned for you; clients find them from MultiConnectSDK key You choose them and give them to clients
Game server list Automatic You keep it current
Adding capacity Change a number on the dashboard; game servers can also scale by themselves, or start one per match Set up a machine, then add its address
Updating your game Build and Deploy; running matches finish on the old build Copy builds and plan the switch yourself
A build that fails to start Rolled back; the previous build keeps serving You notice and restore it
TLS for wss:// In place Your certificate
Analytics Reported and verified for you Sent if you use a free SDK key