private IEnumerator ReadyForPlayers()
        {
            yield return(new WaitForSeconds(.5f));

            // Call this when your game is done initializing and players can connect
            // Note: This is a blocking call, and will return when this game server is either allocated or terminated
            GameserverSDK.ReadyForPlayers();
            if (showDebugMessages)
            {
                Debug.Log("[PlayFabServerInstance] Ready For Players");
            }
            // Call this when your game is done initializing and players can connect
            // Note: This is a blocking call, and will return when this game server is either allocated or terminated
            if (GameserverSDK.ReadyForPlayers())
            {
                // readyForPlayers returns true when an allocation call has been done, a player is about to connect!
                GameserverSDK.LogMessage("GameServer is ready for players");
            }
            else
            {
                // readyForPlayers returns false when the server is being terminated
                GameserverSDK.LogMessage("GameServer is NOT ready for players");
            }
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            // GSDK Setup
            try
            {
                GameserverSDK.Start();
            }
            catch (Microsoft.Playfab.Gaming.GSDK.CSharp.GSDKInitializationException initEx)
            {
                LogMessage("Cannot start GSDK. Please make sure the MockAgent is running. ", false);
                LogMessage($"Got Exception: {initEx.ToString()}", false);
                return;
            }
            catch (Exception ex)
            {
                LogMessage($"Got Exception: {ex.ToString()}", false);
            }

            GameserverSDK.RegisterShutdownCallback(OnShutdown);
            GameserverSDK.RegisterHealthCallback(IsHealthy);
            GameserverSDK.RegisterMaintenanceCallback(OnMaintenanceScheduled);

            // Read our asset file
            if (File.Exists(AssetFilePath))
            {
                _assetFileText = File.ReadAllText(AssetFilePath);
            }

            IDictionary <string, string> initialConfig = GameserverSDK.getConfigSettings();

            // Start the http server
            if (initialConfig?.ContainsKey(ListeningPortKey) == true)
            {
                int    listeningPort = int.Parse(initialConfig[ListeningPortKey]);
                string address       = $"http://*:{listeningPort}/";
                _listener.Prefixes.Add(address);
                _listener.Start();
            }
            else
            {
                LogMessage($"Cannot find {ListeningPortKey} in GSDK Config Settings. Please make sure the MockAgent is running " +
                           $"and that the MultiplayerSettings.json file includes {ListeningPortKey} as a GamePort Name.");
                return;
            }

            // Load our game certificate if it was installed
            if (initialConfig?.ContainsKey(GameCertAlias) == true)
            {
                string    expectedThumbprint = initialConfig[GameCertAlias];
                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, expectedThumbprint, false);

                if (certificateCollection.Count > 0)
                {
                    _installedCertThumbprint = certificateCollection[0].Thumbprint;
                }
                else
                {
                    LogMessage("Could not find installed game cert in LocalMachine\\My. Expected thumbprint is: " + expectedThumbprint);
                }
            }
            else
            {
                LogMessage("Config did not contain cert! Config is: " + string.Join(";", initialConfig.Select(x => x.Key + "=" + x.Value)));
            }

            Thread t = new Thread(ProcessRequests);

            t.Start();

            if (GameserverSDK.ReadyForPlayers())
            {
                _isActivated = true;

                // After allocation, we can grab the session cookie from the config
                IDictionary <string, string> activeConfig = GameserverSDK.getConfigSettings();

                if (activeConfig.TryGetValue(GameserverSDK.SessionCookieKey, out string sessionCookie))
                {
                    LogMessage($"The session cookie from the allocation call is: {sessionCookie}");
                }
            }
            else
            {
                // No allocation happened, the server is getting terminated (likely because there are too many already in standing by)
                LogMessage("Server is getting terminated.");
            }
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            try
            {
                if (args != null && args.Length > 0)
                {
                    _cmdArgs = string.Join(" ", args);
                }

                GameserverSDK.Start(true);
                GameserverSDK.RegisterShutdownCallback(OnShutdown);
                GameserverSDK.RegisterHealthCallback(GetGameHealth);
                GameserverSDK.RegisterMaintenanceCallback(OnMaintenanceScheduled);

                IDictionary <string, string> gsdkConfiguration = GameserverSDK.getConfigSettings();
                if (gsdkConfiguration.TryGetValue("RealPort", out string listeningPortString))
                {
                    _listeningPort = int.Parse(listeningPortString);
                }

                string address = $"http://*:{_listeningPort}/";
                _listener.Prefixes.Add(address);
                _listener.Start();

                string applicationDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (File.Exists(Path.Combine(applicationDirectory, AssetFilePath)))
                {
                    _assetFileText = File.ReadAllText(Path.Combine(applicationDirectory, AssetFilePath));
                }

                // See if we have a configured timeout in the App.config, this was
                // used in our initial round of stress tests to make sure sessions ended
                string timeoutstr = ConfigurationManager.AppSettings.Get(SessionTimeoutInSecondsName);
                if (!string.IsNullOrEmpty(timeoutstr))
                {
                    // failure to convert is intentionally unhandled
                    long timeoutint = Convert.ToInt64(timeoutstr.Trim());

                    _sessionTimeoutTimestamp = DateTimeOffset.Now.AddSeconds(timeoutint);
                }

                IDictionary <string, string> initialConfig = GameserverSDK.getConfigSettings();
                if (initialConfig?.ContainsKey("winRunnerTestCert") == true)
                {
                    string    expectedThumbprint = initialConfig["winRunnerTestCert"];
                    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadOnly);
                    X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, expectedThumbprint, false);

                    if (certificateCollection.Count > 0)
                    {
                        _installedCertThumbprint = certificateCollection[0].Thumbprint;
                    }
                    else
                    {
                        LogMessage("Could not find installed game cert in LocalMachine\\My. Expected thumbprint is: " + expectedThumbprint);
                    }
                }
                else
                {
                    LogMessage("Config did not contain cert! Config is: " + string.Join(";", initialConfig.Select(x => x.Key + "=" + x.Value)));
                }

                Thread t = new Thread(ProcessRequests);
                t.Start();


                string titleId = initialConfig[GameserverSDK.TitleIdKey];
                string buildId = initialConfig[GameserverSDK.BuildIdKey];
                string region  = initialConfig[GameserverSDK.RegionKey];

                LogMessage($"Processing requests for title:{titleId} build:{buildId} in region {region}");

                GameserverSDK.ReadyForPlayers();
                _isActivated = true;

                initialConfig = GameserverSDK.getConfigSettings();

                LogMessage("Config Settings");
                foreach (KeyValuePair <string, string> configTuple in initialConfig)
                {
                    LogMessage($"\t{configTuple.Key}={configTuple.Value}");
                }

                SessionCookie sessionCookie = new SessionCookie();

                if (initialConfig.TryGetValue(GameserverSDK.SessionCookieKey, out string sessionCookieStr))
                {
                    try
                    {
                        if (sessionCookieStr.StartsWith(TimeoutSessionCookiePrefix,
                                                        StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (long.TryParse(sessionCookieStr.Substring(TimeoutSessionCookiePrefix.Length),
                                              out long timeoutSecs))
                            {
                                sessionCookie.TimeoutSecs = timeoutSecs;
                            }
                        }
                        else
                        {
                            sessionCookie = JsonConvert.DeserializeObject <SessionCookie>(sessionCookieStr);
                        }
                    }
                    catch (Exception e)
                    {
                        LogMessage(e.ToString());
                    }
                }

                // If a secret key was specified
                // try to get the title data for this title
                string secretKey = ConfigurationManager.AppSettings.Get(DeveloperSecretKeyName);
                if (!string.IsNullOrWhiteSpace(secretKey))
                {
                    LogMessage("Getting title data");
                    GetTitleData(titleId, secretKey).Wait();
                }
                else
                {
                    LogMessage("Secret Key not specified in app.config. Skipping retrieval of title config");
                }

                // If the session cookie contained a timeout. Shutdown at this time.
                // this overrides whatever may have been set in the App config above
                // We use it for stress testing to make sessions end at random times.
                EnforceTimeout(sessionCookie);
            }
            catch (Exception e)
            {
                LogMessage(e.Message);
                throw;
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            // Test startup
            GameserverSDK.Start();

            GameserverSDK.RegisterShutdownCallback(() => Console.WriteLine("Server is shutting me down!!!!!"));
            GameserverSDK.RegisterHealthCallback(getIsHealthy);
            GameserverSDK.RegisterMaintenanceCallback(maintenanceScheduled);

            // Test grabbing config
            Console.WriteLine("Config before Active.");
            foreach (var config in GameserverSDK.getConfigSettings())
            {
                Console.WriteLine($"{config.Key}: {config.Value}");
            }

            if (GameserverSDK.ReadyForPlayers())
            {
                IList <string> initialPlayers = GameserverSDK.GetInitialPlayers();
                Console.WriteLine("Initial Players: " + string.Join(",", initialPlayers));

                List <ConnectedPlayer> players = new List <ConnectedPlayer>()
                {
                    new ConnectedPlayer("player1"),
                    new ConnectedPlayer("player2")
                };
                GameserverSDK.UpdateConnectedPlayers(players);

                Console.WriteLine("Config after Active.");
                foreach (var config in GameserverSDK.getConfigSettings())
                {
                    Console.WriteLine($"{config.Key}: {config.Value}");
                }

                // Print a rainbow
                int size = 13;
                for (int i = 0; i < 5; i++)
                {
                    String edge   = new String(new char[size]).Replace('\0', ' ');
                    String middle = new String(new char[2 * i]).Replace('\0', ' ');
                    Console.WriteLine(edge + "====" + middle + "=====" + edge);
                    size--;
                }

                for (int i = 0; i < 4; i++)
                {
                    String edge   = new String(new char[size]).Replace('\0', ' ');
                    String middle = new String(new char[10]).Replace('\0', ' ');
                    Console.WriteLine(edge + "====" + middle + "=====" + edge);
                }

                // Leave running a bit more to see the heartbeats
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("...");
                    System.Threading.Thread.Sleep(1000);
                }
            }
            else
            {
                Console.WriteLine("Did not activate, instead shutting down...");
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadKey();
        }
Esempio n. 5
0
        // starts main game process and wait for it to complete
        public static void InitiateAndWaitForGameProcess(string gameserverExe, IEnumerable <string> args)
        {
            // Here we're starting the script that initiates the game process

            activeConfig = GameserverSDK.getConfigSettings();

            // When Wrapper is running in a container, Port Information (Port Name, Port Number, and Protocol) is already set as build configuration.
            // For example, if you already set port number as 80 in container build configuration, activeConfig will return 80 as port number.
            // But if Wrapper is running as a process, port will be mapped internally by MPS, so different number will be dynamically assigned.
            if (activeConfig.TryGetValue(portName, out string listeningPortString))
            {
                GameserverSDK.LogMessage($"{portName}:{listeningPortString} was found in GSDK Config Settings.");
                _listeningPort = listeningPortString;
            }
            else
            {
                LogMessage($"Cannot find {portName} in GSDK Config Settings. Please make sure the LocalMultiplayerAgent is running " +
                           $"and that the MultiplayerSettings.json file includes correct {portName} as a GamePort Name.");
                return;
            }

            // Check if there is any process already using the port (_listeningPort). This will only work for Windows.
            if (CheckIfPortIsUsed(gameserverExe))
            {
                return;
            }
            ;

            // We pass port number as a 3rd argument when we start fakegame.exe
            // Port number is grabbed via GSDK and will be passed to fake game as a listening port.
            gameProcess = StartProcess(gameserverExe, string.Join(' ', args.Append(_listeningPort)));
            // as part of wrapping the main game server executable,
            // we create event handlers to process the output from the game (standard output/standard error)
            // based on this output, we will activate the server and process connected players
            gameProcess.OutputDataReceived += DataReceived;
            gameProcess.ErrorDataReceived  += DataReceived;
            // start reading output (stdout/stderr) from the game
            gameProcess.BeginOutputReadLine();
            gameProcess.BeginErrorReadLine();

            // Call this when your game is done initializing and players can connect
            // Note: This is a blocking call, and will return when this game server is either allocated or terminated
            if (GameserverSDK.ReadyForPlayers())
            {
                // After allocation, we can grab the session cookie from the config
                activeConfig = GameserverSDK.getConfigSettings();

                var connectedPlayers = new List <ConnectedPlayer>();
                // initial players includes the list of the players that are allowed to connect to the game
                // they might or might not end up connecting
                // in this sample we're nevertheless adding them to the list
                foreach (var player in GameserverSDK.GetInitialPlayers())
                {
                    connectedPlayers.Add(new ConnectedPlayer(player));
                }
                GameserverSDK.UpdateConnectedPlayers(connectedPlayers);

                if (activeConfig.TryGetValue(GameserverSDK.SessionCookieKey, out string sessionCookie))
                {
                    LogMessage($"The session cookie from the allocation call is: {sessionCookie}");
                }
            }
            else
            {
                // No allocation happened, the server is getting terminated (likely because there are too many already in standing by)
                LogMessage("Server is getting terminated.");
                gameProcess?.Kill(); // we still need to call WaitForExit https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.kill?view=netcore-3.1#remarks
            }

            // wait till it exits or crashes
            gameProcess.WaitForExit();
        }