Keep a connection alive

Note: Netcode for GameObjects (NGO) automatically keeps connections alive. Check out Using Relay with NGO.

Relay servers automatically disconnect clients after a period of inactivity. The default time to live (TTL) before Relay disconnects a client is 10 seconds. The disconnect TTL is 60 seconds when the host in alone (after the BIND message but before a peer connects to them with a CONNECT message). Any message received by the Relay server involving this client, either as a sender or receiver, resets this timeout.

For games with a lower message frequency, it’s important to keep the connection alive with a method that you regularly call, such as in the Update() loop. If you’re using Relay with NGO, the network manager (NetworkManager) keeps the connection alive automatically. However, it will only do so after you’ve successfully called StartClient or StartHost.

If you’re using Relay with UTP, UTP keeps the connection alive automatically as long as you regularly schedule updates to the NetworkDriver for both host and joining players. You normally do this anyway to accept new connections and receive messages. The following code sample demonstrates code that will keep the connection alive.

//Call the below regularly, e.g., in Monobehaviour.Update()
void Example_KeepingConnectionAlive()
{
    // Update the NetworkDrivers regularly to ensure the host/player is kept online.
    if (HostDriver.IsCreated && isRelayServerConnected)
    {
        HostDriver.ScheduleUpdate().Complete();

        //Accept incoming client connections
        while (HostDriver.Accept() != default(NetworkConnection))
        {
            Debug.Log("Accepted an incoming connection.");
        }
    }

    if (PlayerDriver.IsCreated && clientConnection.IsCreated)
    {
        PlayerDriver.ScheduleUpdate().Complete();

        //Resolve event queue
        NetworkEvent.Type eventType;
        while ((eventType = clientConnection.PopEvent(PlayerDriver, out _)) != NetworkEvent.Type.Empty)
        {
            if (eventType == NetworkEvent.Type.Connect)
            {
                Debug.Log("Client connected to the server");
            }
            else if (eventType == NetworkEvent.Type.Disconnect)
            {
                Debug.Log("Client got disconnected from server");
                clientConnection = default(NetworkConnection);
            }
        }
    }
}