public IEnumerator WaitForConnection(RoomAccessPacket access)
    {
        NetworkManager = NetworkManager ?? FindObjectOfType <NetworkManager>();

        Logger.Debug("Connecting to game server... " + NetworkManager.networkAddress + ":" +
                     NetworkManager.networkPort);

        var timeUntilTimeout = ConnectionTimeout;

        // Wait until we connect
        while (!NetworkManager.IsClientConnected())
        {
            yield return(null);

            timeUntilTimeout -= Time.deltaTime;

            if (timeUntilTimeout < 0)
            {
                Logger.Warn("Client failed to connect to game server: " + access);
                OnFailedToConnect();
                yield break;
            }
        }

        Logger.Info("Connected to game server, about to send access");

        // Connected, send the token
        //NetworkManager.client.connection.Send(UnetGameRoom.AccessMsgType, new StringMessage(access.Token));
        NetworkManager.client.connection.Send(0, UnetGameRoom.AccessMsgType, 0);


        // While connected
        while (NetworkManager.IsClientConnected())
        {
            yield return(null);
        }

        // At this point, we're no longer connected
        if (DisconnectedScene.IsSet())
        {
            SceneManager.LoadScene(DisconnectedScene.SceneName);
        }
    }
Example #2
0
    private void OnAccessReceived(RoomAccessPacket access)
    {
        // Set the access
        UnetRoomConnector.RoomAccess = access;

        if (LoadSceneIfFound && access.Properties.ContainsKey(MsfDictKeys.SceneName))
        {
            var sceneName = access.Properties[MsfDictKeys.SceneName];
            if (sceneName != SceneManager.GetActiveScene().name)
            {
                // If we're at the wrong scene
                SceneManager.LoadScene(sceneName);
            }
            else
            {
                // If we're already at the correct scene
                FindObjectOfType <UnetRoomConnector>().ConnectToGame(access);
            }
        }
    }
Example #3
0
        /// <summary>
        /// Tries to get access data for room we want to connect to
        /// </summary>
        /// <param name="roomId"></param>
        private void GetRoomAccess(int roomId)
        {
            logger.Debug($"Getting access to room {roomId}");

            Mst.Client.Rooms.GetAccess(roomId, (access, error) =>
            {
                if (access == null)
                {
                    logger.Error(error);
                    OnAccessDiniedEvent?.Invoke();
                    return;
                }

                // Save gotten room access
                roomServerAccessInfo = access;

                // Let's set the IP before we start connection
                roomServerIp = roomServerAccessInfo.RoomIp;

                // Let's set the port before we start connection
                roomServerPort = roomServerAccessInfo.RoomPort;

                logger.Debug($"Access to room {roomId} received");
                logger.Debug(access);
                logger.Debug("Connecting to room server...");

                // Start client connection
                //roomServerConnection.UseSsl = MstApplicationConfig.Instance.UseSecure || Mst.Args.UseSecure;
                //roomServerConnection.Connect(roomServerIp, roomServerPort);

                //// Wait a result of client connection
                //roomServerConnection.WaitForConnection((clientSocket) =>
                //{
                //    if (!clientSocket.IsConnected)
                //    {
                //        logger.Error("Connection attempts to room server timed out");
                //        return;
                //    }
                //}, 4f);
            });
        }
Example #4
0
    public IEnumerator WaitForConnection(RoomAccessPacket access)
    {
        NetworkManager = NetworkManager ?? FindObjectOfType <NetworkManager>();
        //	Debug.LogError("Connecting to game server... " + NetworkManager.networkAddress + ":" + NetworkManager.networkPort);

        var timeUntilTimeout = ConnectionTimeout;

        // Wait until we connect
        while (!NetworkManager.IsClientConnected())
        {
            yield return(null);

            timeUntilTimeout -= Time.deltaTime;

            if (timeUntilTimeout < 0)
            {
                Logger.Warn("Client failed to connect to game server: " + access);
                OnFailedToConnect();
                yield break;
            }
        }

        Logger.Info("Connected to game server, about to send access");
        // Connected, send the token
        showDissconnectMsg = true;
        NetworkManager.client.connection.Send(AlbotGameRoom.AccessMsgType, new StringMessage(access.Token));

        // While connected
        while (NetworkManager.IsClientConnected())
        {
            yield return(null);
        }
        // At this point, we're no longer connected
        if (DisconnectedScene.IsSet() && showDissconnectMsg)
        {
            AlbotDialogBox.activateButton(() => { ClientUIStateManager.requestGotoState(ClientUIStates.GameLobby); },
                                          DialogBoxType.GameServerConnLost, "Connection to the gameserver was lost!", "Return to lobby");
        }
    }
Example #5
0
    public override void ConnectToGame(RoomAccessPacket access)
    {
        if (SwitchScenesIfWrongScene &&
            SceneManager.GetActiveScene().name != access.SceneName)
        {
            // Save the access
            RoomAccess = access;

            // Switch to correct scene
            SceneManager.LoadScene(access.SceneName);
            return;
        }

        NetworkManager = NetworkManager ?? FindObjectOfType <NetworkManager>();

        // Remove the data after
        RoomAccess = null;

        // Just in case
        NetworkManager.maxConnections = 999;

        Logger.Debug("Trying to connect to server at address: " + access.RoomIp + ":" + access.RoomPort);

        if (!NetworkManager.IsClientConnected())
        {
            // If we're not connected already
            NetworkManager.networkAddress = access.RoomIp;
            NetworkManager.networkPort    = access.RoomPort;
            NetworkManager.StartClient();
        }

        if (WaitConnectionCoroutine != null)
        {
            StopCoroutine(WaitConnectionCoroutine);
        }

        WaitConnectionCoroutine = StartCoroutine(WaitForConnection(access));
    }
Example #6
0
        /// <summary>
        ///     Tries to get an access to a room with a given room id, password,
        ///     and some other properties, which will be visible to the room (game server)
        /// </summary>
        public void GetAccess(int roomId, RoomAccessCallback callback, string password,
                              Dictionary <string, string> properties)
        {
            if (!Connection.IsConnected)
            {
                callback.Invoke(null, "Not connected");
                return;
            }

            var packet = new RoomAccessRequestPacket
            {
                RoomId     = roomId,
                Properties = properties,
                Password   = password
            };

            Connection.SendMessage((short)OpCodes.GetRoomAccess, packet, (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(null, response.AsString("Unknown Error"));
                    return;
                }

                var access = response.Deserialize(new RoomAccessPacket());

                LastReceivedAccess = access;

                callback.Invoke(access, null);

                AccessReceived?.Invoke(access);

                if (RoomConnector.Instance != null)
                {
                    RoomConnector.Connect(access);
                }
            });
        }
Example #7
0
        /// <summary>
        /// Tries to get access data for room we want to connect to
        /// </summary>
        /// <param name="roomId"></param>
        protected virtual void GetRoomAccess(int roomId)
        {
            logger.Debug($"Getting access to room {roomId}");
            Mst.Events.Invoke(MstEventKeys.showLoadingInfo, $"Getting access to room {roomId}... Please wait!");

            Mst.Client.Rooms.GetAccess(roomId, Mst.Options.AsString(MstDictKeys.ROOM_PASSWORD, string.Empty), (access, error) =>
            {
                if (access == null)
                {
                    Mst.Events.Invoke(MstEventKeys.hideLoadingInfo);
                    logger.Error(error);
                    Mst.Events.Invoke(MstEventKeys.showOkDialogBox,
                                      new OkDialogBoxEventMessage("We could not get access to room. Please try again later or contact to administrator",
                                                                  () =>
                    {
                        if (string.IsNullOrEmpty(RoomNetworkManager.offlineScene))
                        {
                            Mst.Runtime.Quit();
                        }
                        else
                        {
                            SceneManager.LoadScene(RoomNetworkManager.offlineScene);
                        }
                    }));
                    return;
                }

                logger.Debug($"Access to room {roomId} received");
                logger.Debug(access);

                // Save gotten room access
                roomAccess = access;

                // Start joining the room
                JoinTheRoom();
            });
        }
Example #8
0
    private void OnAccessReceived(RoomAccessPacket access)
    {
        // This will be called when you receive an access

        if (access.Properties.ContainsKey(MsfDictKeys.SceneName))
        {
            // In case we received a name of the scene in the access
            // TODO switch scenes if necessary
            Debug.LogError("We might need to change scenes");
            return;
        }

        // We can use it to connect to Unet game server (this is just an example)
        var networkManager = FindObjectOfType <NetworkManager>();

        networkManager.networkAddress = access.RoomIp;
        networkManager.networkPort    = access.RoomPort;

        // Start connecting
        networkManager.StartClient();

        if (WaitConnectionCoroutine != null)
        {
            StopCoroutine(WaitConnectionCoroutine);
        }

        // Wait until connected to server
        WaitConnectionCoroutine = StartCoroutine(WaitForConnection(() =>
        {
            // Client connected to server
            var tokenMsg = new StringMessage(access.Token);

            // Send the token to unet server
            networkManager.client.connection.Send(777, tokenMsg);
        }));
    }
Example #9
0
 /// <summary>
 ///     Should try to connect to game server with data, provided
 ///     in the access packet
 /// </summary>
 /// <param name="access"></param>
 public abstract void ConnectToGame(RoomAccessPacket access);
Example #10
0
        public void ShouldRegisterRoomBeforeFinalizingSpawnTask_AndThen_ShouldReceiveAccessToRoomAsClient()
        {
            var done = new AutoResetEvent(false);

            var spawnId           = -1;
            var spawnCode         = string.Empty;
            var spawnerRegionName = TestContext.CurrentContext.Test.Name;

            //------------------------------------------------------
            //
            // Test-Setup
            //
            // -----------------------------------------------------

            //Fakes spawning a process after receiving a SpawnRequest
            var spawnerDelegateMock = new Mock <ISpawnerRequestsDelegate>();

            spawnerDelegateMock.Setup(mock => mock.HandleSpawnRequest(
                                          It.IsAny <IIncommingMessage>(),
                                          It.Is <SpawnRequestPacket>(packet =>
                                                                     packet.SpawnId >= 0 && !string.IsNullOrEmpty(packet.SpawnCode))))
            .Callback((IIncommingMessage message, SpawnRequestPacket data) =>
            {
                //By default, the spawn-data is passed via commandline-arguments
                spawnId   = data.SpawnId;
                spawnCode = data.SpawnCode;

                message.Respond(ResponseStatus.Success);
                message.Peer.SendMessage((ushort)OpCodes.ProcessStarted, data.SpawnId);
            });

            //------------------------------------------------------
            //
            // On Spawner:
            //
            // Register itself
            //
            // -----------------------------------------------------
            var spawner = new SpeedDateClient();

            spawner.Started += () =>
            {
                spawner.GetPlugin <SpawnerPlugin>().SetSpawnerRequestsDelegate(spawnerDelegateMock.Object);
                spawner.GetPlugin <SpawnerPlugin>().Register(
                    callback: spawnerId =>
                {
                    spawnerId.ShouldBeGreaterThanOrEqualTo(0);
                    done.Set();
                },
                    errorCallback: error => throw new Exception(error));
            };

            spawner.Start(new DefaultConfigProvider(
                              new NetworkConfig(SetUp.MasterServerIp, SetUp.MasterServerPort),
                              PluginsConfig.DefaultSpawnerPlugins, //Load spawner-plugins only
                              new IConfig[]
            {
                new SpawnerConfig
                {
                    Region = spawnerRegionName
                }
            }));

            done.WaitOne(TimeSpan.FromSeconds(30)).ShouldBeTrue(); //The spawner has been registered to master

            //------------------------------------------------------
            //
            // On Client:
            //
            // Connect to the master and request to spawn a new process
            //
            // -----------------------------------------------------
            var client = new SpeedDateClient();

            client.Started += () =>
            {
                client.GetPlugin <AuthPlugin>().LogInAsGuest(info =>
                {
                    client.GetPlugin <SpawnRequestPlugin>().RequestSpawn(new Dictionary <string, string>(),
                                                                         spawnerRegionName,
                                                                         controller =>
                    {
                        controller.ShouldNotBeNull();
                        controller.SpawnId.ShouldBeGreaterThanOrEqualTo(0);
                        controller.Status.ShouldBe(SpawnStatus.None);
                        controller.StatusChanged += status =>
                        {
                            switch (status)
                            {
                            case SpawnStatus.WaitingForProcess:
                            case SpawnStatus.Finalized:
                                done.Set();
                                break;
                            }
                        };
                        spawnId = controller.SpawnId;
                    }, error => throw new Exception(error));
                }, error => throw new Exception(error));
            };

            client.Start(new DefaultConfigProvider(
                             new NetworkConfig(SetUp.MasterServerIp, SetUp.MasterServerPort),
                             PluginsConfig.DefaultPeerPlugins)); //Load peer-plugins only

            done.WaitOne(TimeSpan.FromSeconds(30))
            .ShouldBeTrue();     //The SpawnRequest has been handled and is now waiting for the process to start

            //------------------------------------------------------
            //
            // On Gameserver (which - by default - is started by the spawner):
            //
            // The spawned process now registers itself at the master, starts a new server and then creates a new room
            //
            // -----------------------------------------------------

            var gameserver = new SpeedDateClient();

            gameserver.Started += () =>
            {
                //By default, the spawn-data is passed via commandline-arguments
                gameserver.GetPlugin <RoomsPlugin>().RegisterSpawnedProcess(spawnId, spawnCode,
                                                                            controller =>
                {
                    //By default, these values are passed via commandline-arguments
                    var roomOptions = new RoomOptions
                    {
                        RoomIp   = "127.0.0.1",
                        RoomPort = 20000
                    };
                    gameserver.GetPlugin <RoomsPlugin>().RegisterRoom(roomOptions, roomController =>
                    {
                        controller.FinalizeTask(new Dictionary <string, string>
                        {
                            { OptionKeys.RoomId, roomController.RoomId.ToString() },
                            { OptionKeys.RoomPassword, roomController.Options.Password }
                        }, () =>
                        {
                            //StatusChanged => SpawnStatus.Finalized will signal done
                        });
                    }, error => throw new Exception(error));
                }, error => throw new Exception(error));
            };

            gameserver.Start(new DefaultConfigProvider(
                                 new NetworkConfig(SetUp.MasterServerIp, SetUp.MasterServerPort),
                                 PluginsConfig.DefaultGameServerPlugins)); //Load gameserver-plugins only

            done.WaitOne(TimeSpan.FromSeconds(30))
            .ShouldBeTrue();     //The SpawnRequest has been finalized ('done' is set by StatusChanged.Finalized (see above))

            //------------------------------------------------------
            //
            // On Client:
            //
            // Receive an access-token and connect to the gameserver
            //
            // -----------------------------------------------------
            RoomAccessPacket roomAccess = null;

            client.GetPlugin <SpawnRequestPlugin>().GetRequestController(spawnId).ShouldNotBeNull();
            client.GetPlugin <SpawnRequestPlugin>().GetRequestController(spawnId).GetFinalizationData(data =>
            {
                data.ShouldNotBeNull();
                data.ShouldContainKey(OptionKeys.RoomId);
                data.ShouldContainKey(OptionKeys.RoomPassword);

                client.GetPlugin <RoomPlugin>().GetAccess(
                    roomId: Convert.ToInt32(data[OptionKeys.RoomId]),
                    password: data[OptionKeys.RoomPassword],
                    properties: new Dictionary <string, string>(),
                    callback: access =>
                {
                    roomAccess = access;
                    done.Set();
                },
                    errorCallback: error => throw new Exception(error));
            },
                                                                                                      error => throw new Exception(error));

            done.WaitOne(TimeSpan.FromSeconds(30)).ShouldBeTrue(); //Client received RoomAccess

            //------------------------------------------------------
            //
            // Now the client has to connect to the gameserver and transmit the token.
            // How this is done is out of SpeedDate's scope. You may use UNET, LiteNetLib, TcpListener, another SpeedDate server or any other custom solution.
            //
            // This test simply uses the same access-object on the server and the client
            //
            // -----------------------------------------------------

            gameserver.GetPlugin <RoomsPlugin>().ValidateAccess(roomAccess.RoomId, roomAccess.Token, id =>
            {
                id.PeerId.ShouldBe(client.PeerId);
                done.Set();
            }, error => throw new Exception(error));
            done.WaitOne(TimeSpan.FromSeconds(30)).ShouldBeTrue(); //Gameserver validated access
        }
Example #11
0
        /// <summary>
        ///     This method triggers the <see cref="AccessReceived" /> event. Call this,
        ///     if you made some custom functionality to get access to rooms
        /// </summary>
        /// <param name="access"></param>
        public void TriggerAccessReceivedEvent(RoomAccessPacket access)
        {
            LastReceivedAccess = access;

            AccessReceived?.Invoke(access);
        }
Example #12
0
 private void joinedGame(RoomAccessPacket p)
 {
     setUIState(ClientUIStates.PlayingGame);
 }