static async void Initialize() { try { GameserverSDK.Start(); LoadConfig(); GameserverSDK.RegisterShutdownCallback(() => { g_ServerProcess.Kill(); }); } catch { g_bIsRunningInComputeEnvironment = false; g_HttpClient = new HttpClient(); g_HttpClient.DefaultRequestHeaders.Add("Authorization", strAuthHeader); // We're running in a dev environment, so lets dummy add our server RegisterAsDevelopmentServer(); } LaunchServer(); await g_IPC.Connect(); if (g_bIsRunningInComputeEnvironment) { GameserverSDK.ReadyForPlayers(); g_bServerAllocated = true; g_bPendingServerAllocationIPCMsg = true; } }
private void Start() { //Retrieves the EntityToken GetEntityToken(); // Get all the configuration values config = GameserverSDK.getConfigSettings(); Debug.Log("[PlayFabServerInstance] Received PlayFab Config"); connectionInfo = GameserverSDK.GetGameServerConnectionInfo(); //Retrieve a particular configuration value if (config.TryGetValue(GameserverSDK.SessionCookieKey, out string sessionCookie)) { //sessionCookie contains the value } _connectedPlayers = new List <Microsoft.Playfab.Gaming.GSDK.CSharp.ConnectedPlayer>(); // This will add your log line the GSDK log file, alongside other information logged by the GSDK GameserverSDK.LogMessage("[PlayFabServerInstance] GameServer Starting"); Debug.Log("[PlayFabServerInstance] GameServer Starting"); // Alternatively, you can log your own files to the log directory string logFolder = GameserverSDK.GetLogsDirectory(); // Call this while your game is initializing, it will start heartbeating to our agent and put the game server in an Initializing state GameserverSDK.Start(); GameserverSDK.RegisterShutdownCallback(OnShutdown); GameserverSDK.RegisterMaintenanceCallback(OnMaintenanceScheduled); GameserverSDK.RegisterHealthCallback(IsHealthy); /* Add any other initializion code your game server needs before players can connect */ }
// GSDK event handlers - we're setting them on the startup of the app public static void RegisterGSDKCallbacksAndStartGSDK() { // OnShutDown will be called when developer calls the ShutdDownMultiplayerServer API // https://docs.microsoft.com/en-us/rest/api/playfab/multiplayer/multiplayerserver/shutdownmultiplayerserver?view=playfab-rest GameserverSDK.RegisterShutdownCallback(OnShutdown); // This callback will be called on every heartbeat to check if your game is healthy. So it should return quickly GameserverSDK.RegisterHealthCallback(IsHealthy); // this callback will be called to notify us that Azure will perform maintenance on the VM // you can see more details about Azure VM maintenance here https://docs.microsoft.com/en-gb/azure/virtual-machines/maintenance-and-updates?toc=/azure/virtual-machines/windows/toc.json&bc=/azure/virtual-machines/windows/breadcrumb/toc.json GameserverSDK.RegisterMaintenanceCallback(OnMaintenanceScheduled); // Call this while your game is initializing; it will start sending a heartbeat to our agent // since our game server will transition to a standingBy state, we should call this when we're confident that our game server will not crash // here we're calling it just before we start our game server process - normally we would call it inside our game code GameserverSDK.Start(); }
public ChessBackEnd(PluginLoadData pluginLoadData) : base(pluginLoadData) { ClientManager.ClientConnected += ClientConnected; ClientManager.ClientDisconnected += ClientDisconnected; GameserverSDK.RegisterShutdownCallback(OnShutdown); GameserverSDK.RegisterHealthCallback(OnHealthCheck); // Connect to PlayFab agent GameserverSDK.Start(); if (GameserverSDK.ReadyForPlayers()) { // returns true on allocation call, player about to connect } else { // returns false when server is being terminated } }
public NetworkManager(PluginLoadData pluginLoadData) : base(pluginLoadData) { GameserverSDK.Start(); ClientManager.ClientConnected += ClientConnected; ClientManager.ClientDisconnected += ClientDisconnected; GameserverSDK.RegisterShutdownCallback(OnShutdown); GameserverSDK.RegisterHealthCallback(OnHealthCheck); sessionIdAssigned = false; if (GameserverSDK.ReadyForPlayers()) { // returns true on allocation call, player about to connect } else { // returns false when server is being terminated } }
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."); } }
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(); }
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; } }