Пример #1
0
        public void OnOpen(IWebSocketConnection socket)
        {
            Logger.Log(this, "A connection was opened. (Socket ID: {0})", socket.ConnectionInfo.Id);

            // Respond to a join request by assigning a unique ID to the connection and sending it back to the client
            var player = AddPlayer(socket);

            player.RequestClientInfo();

            // Wait for player reponse with their name
            player.Socket.OnBinary += (binary) =>
            {
                // Messages are sent as binary from Unity (the WebGL wrapper only sends binary for some reason)
                var message = Encoding.UTF8.GetString(binary);

                Message.IsType <ClientMessage.GiveClientInfo>(message, (data) =>
                {
                    if (data.ProtocolVersion != ProtocolInfo.Version)
                    {
                        // Notify protocol mismatch. Client and Server must match!
                        player.SendConnectionError(ConnectionError.ProtocolMismatch);
                        return;
                    }

                    // Check if name is within character range
                    bool nameWithinCharLimit = data.Name.Length >= SettingsLoader.Values.Server.NameMinChars && data.Name.Length <= SettingsLoader.Values.Server.NameMaxChars;

                    // Check if an existing connection already has that name
                    bool nameisUnique = !ConnectedPlayers.Any(x => x.Data.Name.ToLower() == data.Name.ToLower());

                    if (nameWithinCharLimit && nameisUnique)
                    {
                        OnConnectionSuccessful(player, data);
                    }
                    else if (!nameWithinCharLimit)
                    {
                        player.SendConnectionError(ConnectionError.InvalidNameLength);
                    }
                    else
                    {
                        player.SendConnectionError(ConnectionError.MatchesExistingName);
                    }
                });
            };
        }