示例#1
0
    /**
     * Sets up new controller connections or reconnects controllers which lost their connection.
     */
    private void HandleConnectionSetup(string name, int connectionId, string websocketId)
    {
        // check if there is already a player of this name...
        if (_clients.TryGetPlayerId(name, out var playerId))
        {
            if (_clients.TryGetInput(playerId, out var input))
            {
                // if the controller of that player is still connected, deny the connection
                if (input.IsConnected())
                {
                    SendToByWebsocketId(websocketId, new Message.NameTakenMessage(name));
                }

                // otherwise, its a controller which tries to reconnect, so we accept it
                else
                {
                    _clients.SetNewConnectionInfo(playerId, connectionId, websocketId);
                    SendToByWebsocketId(websocketId, new Message.NameOkMessage());
                    input.SetStatus(ConnectionStatus.Connected);
                }
            }

            else
            {
                LogError("There is an established player id without an input object. This should never happen and is a programming error.");
            }
        }

        // ...otherwise, this is an entirely new player
        else
        {
            // if we have not yet reached the maximum number of players, we can accept the new controller
            if (_clients.ClientCount() < _maxNumPlayers)
            {
                var newInput = _clients.NewClient(
                    name,
                    connectionId,
                    websocketId,
                    newPlayerId => new ControllerInput(newPlayerId, name, new PlayerInfo(), this)
                    );
                newInput.SetStatus(ConnectionStatus.Connected);

                Log($"Accepted new player of name {name}");
                SendToByWebsocketId(websocketId, new Message.NameOkMessage());

                OnNewController?.Invoke(newInput);
            }

            // otherwise we have to deny establishing a connection
            else
            {
                Log("Controller tried to connect, but the maximum number of players has already been reached.");
                SendToByWebsocketId(websocketId, new Message.MaxPlayersReachedMessage());
            }
        }
    }