public bool TryJoinLobby(int id, string password)
        {
            var request = new WithoutLobbyRequest();
            var message = new JoinLobbyRequest();

            message.Password         = password;
            message.LobbyId          = id;
            request.JoinLobbyRequest = message;

            System.Console.WriteLine($"Joining lobby {id}");

            request.WriteDelimitedTo(stream);

            var response = JoinLobbyResponse.Parser.ParseDelimitedFrom(stream);

            if (response.LobbyInfo != null)
            {
                System.Console.WriteLine($"Successfully joined lobby: {response.LobbyInfo}");
                this.state        = Tcp_State.PeerWithinLobby;
                this.joined_lobby = response.LobbyInfo;
                return(true);
            }

            this.state = Tcp_State.WithoutLobby;
            return(false);
        }
        public static async Task <string> MakeLobby(string userId)
        {
            var joinLobbyRequest = new JoinLobbyRequest
            {
                DisplayName  = "TestUser",
                LobbyId      = "dummmmyyyy",
                SelfPortrait = Constants.Drawings.GrayDot
            };

            await WebClient.MakeWebRequest(
                path : Constants.Path.LobbyCreate,
                userId : userId,
                method : HttpMethod.Post,
                content : new StringContent(
                    JsonConvert.SerializeObject(joinLobbyRequest),
                    Encoding.UTF8,
                    Constants.MediaType.ApplicationJson));

            Thread.Sleep(100);
            HttpResponseMessage getLobbyResponse = await WebClient.MakeWebRequest(
                path : Constants.Path.LobbyGet,
                userId : userId,
                method : HttpMethod.Get);

            LobbyMetadataResponse lobbyGetResponse = JsonConvert.DeserializeObject <LobbyMetadataResponse>(await getLobbyResponse.Content.ReadAsStringAsync());

            return(lobbyGetResponse.LobbyId);
        }
Exemple #3
0
        protected virtual OperationResponse HandleJoinLobby(MasterClientPeer peer, OperationRequest operationRequest, SendParameters sendParameters)
        {
            // validate operation
            var operation = new JoinLobbyRequest(peer.Protocol, operationRequest);
            OperationResponse response;

            if (OperationHelper.ValidateOperation(operation, log, out response) == false)
            {
                return(response);
            }

            // special handling for game properties send by AS3/Flash (Amf3 protocol) clients
            if (peer.Protocol.ProtocolType == ProtocolType.Amf3V151 || peer.Protocol.ProtocolType == ProtocolType.Amf3V152)
            {
                Utilities.ConvertAs3WellKnownPropertyKeys(operation.GameProperties, null);
            }

            peer.GameChannelSubscription = null;

            var subscription = this.GameList.AddSubscription(peer, operation.GameProperties, operation.GameListCount);

            peer.GameChannelSubscription = subscription;
            peer.SendOperationResponse(new OperationResponse(operationRequest.OperationCode), sendParameters);

            // publish game list to peer after the response has been sent
            var gameList = subscription.GetGameList();
            var e        = new GameListEvent {
                Data = gameList
            };
            var eventData = new EventData((byte)EventCode.GameList, e);

            peer.SendEvent(eventData, new SendParameters());

            return(null);
        }
Exemple #4
0
        protected virtual OperationResponse HandleJoinLobby(MasterClientPeer peer, JoinLobbyRequest operation, SendParameters sendParameters)
        {
            try
            {
                // special handling for game properties send by AS3/Flash (Amf3 protocol) clients
                if (peer.Protocol.ProtocolType == ProtocolType.Amf3V152 || peer.Protocol.ProtocolType == ProtocolType.Json)
                {
                    Utilities.ConvertAs3WellKnownPropertyKeys(operation.GameProperties, null);
                }

                peer.GameChannelSubscription = null;

                var subscription = this.GameList.AddSubscription(peer, operation.GameProperties, operation.GameListCount);
                peer.GameChannelSubscription = subscription;
                peer.SendOperationResponse(new OperationResponse(operation.OperationRequest.OperationCode), sendParameters);


                // publish game list to peer after the response has been sent
                var gameList = subscription.GetGameList();
                var e        = new GameListEvent {
                    Data = gameList
                };
                var eventData = new EventData((byte)EventCode.GameList, e);
                peer.SendEvent(eventData, new SendParameters());

                return(null);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return(null);
            }
        }
Exemple #5
0
        public async Task JoinLobby(JoinLobbyRequest request)
        {
            var result = await _mediator.Send(request);

            await Groups.AddToGroupAsync(Context.ConnectionId, LOBBY);

            await Clients.Client(Context.ConnectionId).SendAsync("PlayerJoinedLobby", result.Games);
        }
        public OperationResponse HandleJoinLobby(OperationRequest operationRequest, SendParameters sendParameters)
        {
            var joinLobbyRequest = new JoinLobbyRequest(this.Protocol, operationRequest);

            OperationResponse response;

            if (OperationHelper.ValidateOperation(joinLobbyRequest, log, out response) == false)
            {
                return(response);
            }

            if (joinLobbyRequest.LobbyType > 3)
            {
                return(new OperationResponse
                {
                    OperationCode = operationRequest.OperationCode,
                    ReturnCode = (short)ErrorCode.OperationInvalid,
                    DebugMessage = "Invalid lobby type " + joinLobbyRequest.LobbyType
                });
            }

            // remove peer from the currently joined lobby
            if (this.AppLobby != null)
            {
                this.AppLobby.RemovePeer(this);
                this.AppLobby = null;
            }

            AppLobby lobby;

            if (!this.Application.LobbyFactory.GetOrCreateAppLobby(joinLobbyRequest.LobbyName, (AppLobbyType)joinLobbyRequest.LobbyType, out lobby))
            {
                // getting here should never happen
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("Could not get or create lobby: name={0}, type={1}", joinLobbyRequest.LobbyName, (AppLobbyType)joinLobbyRequest.LobbyType);
                }
                return(new OperationResponse
                {
                    OperationCode = operationRequest.OperationCode,
                    ReturnCode = (short)ErrorCode.InternalServerError,
                    DebugMessage = LBErrorMessages.CanNotCreateLobby,
                });
            }

            this.AppLobby = lobby;
            this.AppLobby.JoinLobby(this, joinLobbyRequest, sendParameters);

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Joined lobby: {0}, {1}, u:'{2}'", joinLobbyRequest.LobbyName, joinLobbyRequest.LobbyType, this.UserId);
            }

            return(null);
        }
Exemple #7
0
        protected virtual OperationResponse HandleJoinLobby(MasterClientPeer peer, JoinLobbyRequest operation, SendParameters sendParameters)
        {
            try
            {
                peer.GameChannelSubscription = null;

                if (operation.GameListCount > 0 && this.gameListLimit > 0)
                {
                    if (operation.GameListCount > this.gameListLimit)
                    {
                        operation.GameListCount = this.gameListLimit;
                    }
                }

                var subscription = this.GameList.AddSubscription(peer, operation.GameProperties, operation.GameListCount);
                peer.GameChannelSubscription = subscription;
                peer.SendOperationResponse(new OperationResponse(operation.OperationRequest.OperationCode), sendParameters);


                if (subscription != null)
                {
                    // publish game list to peer after the response has been sent
                    var gameList = subscription.GetGameList();

                    if (gameList.Count != 0)
                    {
                        var sb = new StringBuilder();
                        foreach (var game in gameList.Keys)
                        {
                            sb.AppendFormat("{0};", game);
                        }

                        if (log.IsDebugEnabled)
                        {
                            log.DebugFormat("Game list is: {0}", sb.ToString());
                        }
                    }

                    var e = new GameListEvent {
                        Data = gameList
                    };
                    var eventData = new EventData((byte)EventCode.GameList, e);
                    peer.SendEvent(eventData, new SendParameters());
                }

                this.peers.Add(peer);
                return(null);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return(null);
            }
        }
Exemple #8
0
        protected virtual void ExecuteOperation(MasterClientPeer peer, OperationRequest operationRequest, SendParameters sendParameters)
        {
            try
            {
                OperationResponse response;

                switch ((OperationCode)operationRequest.OperationCode)
                {
                default:
                    response = new OperationResponse(operationRequest.OperationCode)
                    {
                        ReturnCode = -1, DebugMessage = "Unknown operation code"
                    };
                    break;

                case OperationCode.JoinLobby:
                    var joinLobbyRequest = new JoinLobbyRequest(peer.Protocol, operationRequest);
                    if (OperationHelper.ValidateOperation(joinLobbyRequest, log, out response))
                    {
                        response = this.HandleJoinLobby(peer, joinLobbyRequest, sendParameters);
                    }
                    break;

                case OperationCode.LeaveLobby:
                    response = this.HandleLeaveLobby(peer, operationRequest);
                    break;

                case OperationCode.CreateGame:
                    response = this.HandleCreateGame(peer, operationRequest);
                    break;

                case OperationCode.JoinGame:
                    response = this.HandleJoinGame(peer, operationRequest);
                    break;

                case OperationCode.JoinRandomGame:
                    response = this.HandleJoinRandomGame(peer, operationRequest);
                    break;

                case OperationCode.DebugGame:
                    response = this.HandleDebugGame(peer, operationRequest);
                    break;
                }

                if (response != null)
                {
                    peer.SendOperationResponse(response, sendParameters);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
    public async Task <JoinLobbyResponse> JoinLobby(string lobbyName)
    {
        MessageListener <JoinLobbyResponse> joinLobbyResponseListener = new MessageListener <JoinLobbyResponse>();

        joinLobbyResponseListener.Subscribe(_messageProcessor);
        JoinLobbyRequest joinLobbyRequest = new JoinLobbyRequest(Guid.NewGuid(), _loggedInUser, lobbyName);
        await _networkConnector.SendMessageAsync(joinLobbyRequest, CancellationToken.None);

        JoinLobbyResponse joinLobbyResponse = await joinLobbyResponseListener.ReceiveMessageAsync();

        joinLobbyResponseListener.Unsubscribe();
        return(joinLobbyResponse);
    }
Exemple #10
0
        public IActionResult JoinLobby([FromBody] JoinLobbyRequest request, [FromQuery(Name = "Id")] string id)
        {
            if (!ModelState.IsValid || request == null)
            {
                return(new BadRequestResult());
            }

            (bool success, string error) = InternalJoinLobby(request, id);
            if (!success)
            {
                return(StatusCode(400, error));
            }
            return(new OkResult());
        }
Exemple #11
0
        private (bool, string) InternalJoinLobby(JoinLobbyRequest request, string id)
        {
            if (!Sanitize.SanitizeString(request.DisplayName, out string _))
            {
                return(false, "DisplayName invalid.");
            }

            if (!Sanitize.SanitizeString(request.LobbyId, out string _))
            {
                return(false, "LobbyId invalid.");
            }

            User user = GameManager.MapIdentifierToUser(id, out bool newUser);

            lock (user.LockObject)
            {
                if (user.Lobby != null & user.LobbyId == request.LobbyId)
                {
                    // Another thread beat us to it. Return generic error.
                    return(false, "Try Again.");
                }

                if (user.Lobby != null)
                {
                    // Either another thread beat us to it (with multiple lobbies). Or we got the user stuck in a bad state.
                    // Unregister the user and return failure.
                    GameManager.UnregisterUser(user);
                    return(false, "Try Again.");
                }

                (bool, string)result = GameManager.RegisterUser(user, request);
                if (!result.Item1)               // Check success.
                {
                    return(false, result.Item2); // Return error message.
                }

                if (user?.Lobby == null) // Confirm user is now in a lobby.
                {
                    return(false, "Unknown error occurred while joining Lobby.");
                }

                return(true, string.Empty);
            }
        }
Exemple #12
0
        public async Task <IActionResult> JoinLobby([FromBody] JoinLobbyRequest request)
        {
            Guid lobbyId = _registry.JoinLobby(request.HostId, request.JoineeId);

            ServerSidePlayer joinee = _registry.GetPlayerById(request.JoineeId);

            List <ServerSidePlayer> members = _registry.GetLobbyMembers(request.HostId);

            await _hubContext.Clients.Group(lobbyId.ToString()).NewPlayerInLobby(new ServerSidePlayerOverview {
                Id        = joinee.Id,
                AvatarUrl = joinee.AvatarUrl,
                Name      = joinee.Name,
            });

            return(base.Ok(new JoinLobbyResponse {
                LobbyId = lobbyId,
                Members = GetOverviewFromPlayer(members)
            }));
        }
        public OperationResponse HandleJoinLobby(OperationRequest operationRequest, SendParameters sendParameters)
        {
            var joinLobbyRequest = new JoinLobbyRequest(this.Protocol, operationRequest);

            OperationResponse response;

            if (OperationHelper.ValidateOperation(joinLobbyRequest, log, out response) == false)
            {
                return(response);
            }

            // remove peer from the currently joined lobby
            if (this.AppLobby != null)
            {
                this.AppLobby.RemovePeer(this);
                this.AppLobby = null;
            }

            AppLobby lobby;

            if (!this.Application.LobbyFactory.GetOrCreateAppLobby(joinLobbyRequest.LobbyName, (AppLobbyType)joinLobbyRequest.LobbyType, out lobby))
            {
                return(new OperationResponse
                {
                    OperationCode = operationRequest.OperationCode,
                    ReturnCode = (short)ErrorCode.OperationDenied,
                    DebugMessage = "Cannot create lobby"
                });
            }

            this.AppLobby = lobby;
            this.AppLobby.JoinLobby(this, joinLobbyRequest, sendParameters);

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Joined lobby: {0}, {1}", joinLobbyRequest.LobbyName, joinLobbyRequest.LobbyType);
            }

            return(null);
        }
        public static async Task JoinLobby(string userId, string lobbyId, string name = null, string drawing = null)
        {
            Debug.Assert(userId.Length == 50);
            name ??= "TestUser";
            drawing ??= Constants.Drawings.GrayDot;

            var joinLobbyRequest = new JoinLobbyRequest
            {
                DisplayName  = name,
                LobbyId      = lobbyId,
                SelfPortrait = drawing
            };

            var httpResponseMessage = await WebClient.MakeWebRequest(
                path : Constants.Path.LobbyJoin,
                userId : userId,
                method : HttpMethod.Post,
                content : new StringContent(
                    JsonConvert.SerializeObject(joinLobbyRequest),
                    Encoding.UTF8,
                    Constants.MediaType.ApplicationJson));

            await httpResponseMessage.ThrowIfNonSuccessResponse(userId);
        }
Exemple #15
0
 public (bool, string) RegisterUser(User user, JoinLobbyRequest request)
 {
     return(RegisterUser(request.LobbyId, user, request.DisplayName, request.SelfPortrait));
 }
Exemple #16
0
 public void JoinLobby(MasterClientPeer peer, JoinLobbyRequest joinLobbyrequest, SendParameters sendParameters)
 {
     this.ExecutionFiber.Enqueue(() => this.HandleJoinLobby(peer, joinLobbyrequest, sendParameters));
 }
Exemple #17
0
        //   [Authorize(Policy = "LobbyManagement")]
#endif
        public IActionResult CreateLobby([FromBody] JoinLobbyRequest request, [FromQuery(Name = "Id")] string id)
        {
            request.LobbyId = "temp"; // This should hopefully make LobbyId optional to the modelstate.
            if (!ModelState.IsValid)
            {
                return(new BadRequestResult());
            }
            AuthenticatedUser user = GameManager.GetAuthenticatedUser(this.HttpContext.User.GetUserId(id));

            if (user == null)
            {
                return(StatusCode(500, "Something went wrong finding that user, try again"));
            }

            if (user.OwnedLobby != null)
            {
                return(new OkResult());
            }

            lock (user.Lock)
            {
                if (user.OwnedLobby != null)
                {
                    return(new OkResult());
                }

                string lobbyId;
                int    safety = 0;
                do
                {
                    // Keep making lobbyIds until a new one is found
                    lobbyId = Guid.NewGuid().ToString().Substring(0, 5);
                    if (safety++ > 20)
                    {
                        throw new Exception("Yikes");
                    }
                } while (GameManager.GetLobby(lobbyId) != null);

                Lobby newLobby = ActivatorUtilities.CreateInstance <Lobby>(this.ServiceProvider, lobbyId, user);

                if (!GameManager.RegisterLobby(newLobby))
                {
                    return(StatusCode(500, "Failed to create lobby, try again"));
                }

                request.LobbyId = lobbyId;
                (bool, string)joinLobbyResponse;
                try
                {
                    joinLobbyResponse = InternalJoinLobby(request, id);
                }
                catch
                {
                    joinLobbyResponse = (false, "Internal Error");
                }
                if (!joinLobbyResponse.Item1)
                {
                    GameManager.DeleteLobby(lobbyId);
                    return(StatusCode(400, joinLobbyResponse.Item2));
                }

                user.OwnedLobby = newLobby;
                return(Ok(lobbyId));
            }
        }
Exemple #18
0
        /// <inheritdoc/>
        public JoinLobbyResult JoinLobby(JoinLobbyRequest request)
        {
            try
            {
                lock (this.Padlock)
                {
                    if (this.LobbyMode == Mode.GameOver)
                    {
                        return(new JoinLobbyResult()
                        {
                            Success = false,
                            Details = "Lobby has been closed.",
                        });
                    }

                    if (request.Password != this.Password)
                    {
                        return(new JoinLobbyResult()
                        {
                            Success = false,
                            Details = "Password was not correct.",

                            LobbyId = this.Id,
                        });
                    }

                    // Find access token
                    long accessToken;
                    do
                    {
                        accessToken = ServerRandom.RandomLong;
                    }while (this.AccessTokens.Contains(accessToken));

                    if (!this.Broadcaster.TryAssociateWithConnection(accessToken, request.ConnectionNumber))
                    {
                        return(new JoinLobbyResult()
                        {
                            Success = false,
                            Details = "Connection number was not found to map to a valid open connection to the server.",

                            LobbyId = this.Id,
                        });
                    }

                    _ = this.AccessTokens.Add(accessToken);
                    this.PlayerCount++;

                    this.Broadcaster.Ping();

                    if (this.LobbyMode == Mode.InputMode)
                    {
                        this.EcsContainer.UpdateClientSystem.UpdateClients();
                    }
                    else if (this.LobbyMode == Mode.FightMode)
                    {
                        this.DelayedUpdate = true;
                    }

                    return(new JoinLobbyResult()
                    {
                        AccessToken = accessToken,
                        LobbyId = this.Id,
                    });
                }
            }
            finally
            {
                this.ResetInactivityTimer();
            }
        }