保持连接活跃

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

中继服务器会自动断开一段空闲时间后的客户端连接。中继在断开客户端连接之前的默认生存时间 (TTL) 为 **10 秒**。当主机处于独占状态(在发送 `BIND` 消息但连接到它们的端点 (peer) 发送 `CONNECT` 消息之前)时,断开连接 TTL 为 **60 秒**。中继服务器接收到的任何与该客户端相关的消息,无论是作为发送方还是接收方,都会重置此超时

对于消息频率较低的游戏,使用定期调用的方法来保持连接活跃非常重要,例如在 `Update()` 循环中。如果使用的是中继与 NGO,网络管理器 (NetworkManager) 会自动保持连接活跃。但是,它只有在成功调用StartClientStartHost 之后才会执行此操作。

如果使用的是中继与 UTP,只要定期为主机和加入的玩家调度NetworkDriver 更新,UTP 就会自动保持连接活跃。通常,你总是会这样做以接受新连接和接收消息。以下代码示例演示了将保持连接活跃的代码。

//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);
            }
        }
    }
}