public void TerminateGameSession(bool processEnding) { if (GameLiftRequestedTermination) { // don't terminate game session if gamelift initiated process termination, just exit. Environment.Exit(0); } try { var outcome = GameLiftServerAPI.TerminateGameSession(); if (outcome.Success) { Debug.Log(":) GAME SESSION TERMINATED"); if (processEnding) { ProcessEnding(); } else { ProcessReady(); } } else { Debug.Log(":( GAME SESSION TERMINATION FAILED. TerminateGameSession() returned " + outcome.Error.ToString()); } } catch (Exception e) { Debug.Log(":( GAME SESSION TERMINATION FAILED. TerminateGameSession() exception " + Environment.NewLine + e.Message); } }
static void Main(string[] args) { Console.WriteLine("Starting the server at port: " + PORT); GenericOutcome outcome = GameLiftServerAPI.InitSDK(); if (outcome.Success) { /* * short[] messageTypes = { * MsgType.Connect, MsgType.Disconnect, Messages.ACCEPT_PLAYER_SESSION, Messages.START_LOCAL_GAME, * Messages.START_GAME, Messages.SUBMIT_COMMANDS, Messages.END_GAME, * }; * Util.ToList(messageTypes).ForEach(messageType => NetworkServer.RegisterHandler(messageType, GetHandler(messageType))); */ UdpClient udpClient = new UdpClient(PORT); udpClient.BeginReceive(DataReceived, udpClient); LogParameters paths = new LogParameters(); paths.LogPaths.Add("C:\\Game\\logs"); GameLiftServerAPI.ProcessReady(new ProcessParameters( OnGameSession, OnProcessTerminate, OnHealthCheck, PORT, paths )); Console.WriteLine("Listening on: " + PORT); Console.ReadKey(); } else { Console.WriteLine(outcome); } }
public void DisconnectPlayer(int playerIdx) { // if player slots never re-open, just skip this entire thing. try { string playerSessionId = playerSessions[playerIdx]; try { var outcome = GameLiftServerAPI.RemovePlayerSession(playerSessionId); if (outcome.Success) { Debug.Log(":) PLAYER SESSION REMOVED"); } else { Debug.Log(":( PLAYER SESSION REMOVE FAILED. RemovePlayerSession() returned " + outcome.Error.ToString()); } } catch (Exception e) { Debug.Log(":( PLAYER SESSION REMOVE FAILED. RemovePlayerSession() exception " + Environment.NewLine + e.Message); throw; } playerSessions.Remove(playerIdx); } catch (KeyNotFoundException e) { Debug.Log(":( INVALID PLAYER SESSION. Exception " + Environment.NewLine + e.Message); throw; // should never happen } }
private void SetupServerAndGamelift() { // start the unet server //todo commented by dan //networkPort = LISTEN_PORT; //StartServer(); //print($"Server listening on port {networkPort}"); // initialize GameLift print("Starting GameLift initialization."); var initSDKOutcome = GameLiftServerAPI.InitSDK(); if (initSDKOutcome.Success) { isGameliftServer = true; var processParams = new ProcessParameters( (gameSession) => { // onStartGameSession callback GameLiftServerAPI.ActivateGameSession(); // quit if no player joined within two minutes timer.Elapsed += this.CheckPlayersJoined; timer.AutoReset = false; timer.Start(); }, (updateGameSession) => { }, () => { // onProcessTerminate callback TerminateSession(); }, () => { // healthCheck callback return(true); }, LISTEN_PORT, new LogParameters(new List <string>() { "/local/game/logs/myserver.log" }) ); var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParams); if (processReadyOutcome.Success) { print("GameLift process ready."); } else { print($"GameLift: Process ready failure - {processReadyOutcome.Error.ToString()}."); } } else { print($"GameLift: InitSDK failure - {initSDKOutcome.Error.ToString()}."); } }
public override void Disconnected(BoltConnection connection) { if (BoltNetwork.IsServer) { GameLiftServerAPI.RemovePlayerSession((string)connection.UserData); } }
//This is an example of a simple integration with GameLift server SDK that makes game server //processes go active on Amazon GameLift public void Start() { //InitSDK establishes a local connection with the Amazon GameLift agent to enable //further communication. var initSDKOutcome = GameLiftServerAPI.InitSDK(); if (initSDKOutcome.Success) { ProcessParameters processParameters = new ProcessParameters( (gameSession) => { //Respond to new game session activation request. GameLift sends activation request //to the game server along with a game session object containing game properties //and other settings. Once the game server is ready to receive player connections, //invoke GameLiftServerAPI.ActivateGameSession() GameLiftServerAPI.ActivateGameSession(); }, () => { //OnProcessTerminate callback. GameLift invokes this callback before shutting down //an instance hosting this game server. It gives this game server a chance to save //its state, communicate with services, etc., before being shut down. //In this case, we simply tell GameLift we are indeed going to shut down. GameLiftServerAPI.ProcessEnding(); }, () => { //This is the HealthCheck callback. //GameLift invokes this callback every 60 seconds or so. //Here, a game server might want to check the health of dependencies and such. //Simply return true if healthy, false otherwise. //The game server has 60 seconds to respond with its health status. //GameLift will default to 'false' if the game server doesn't respond in time. //In this case, we're always healthy! return(true); }, //Here, the game server tells GameLift what port it is listening on for incoming player //connections. In this example, the port is hardcoded for simplicity. Active game //that are on the same instance must have unique ports. listeningPort, new LogParameters(new List <string>() { //Here, the game server tells GameLift what set of files to upload when the game session ends. //GameLift uploads everything specified here for the developers to fetch later. "/local/game/logs/myserver.log" })); //Calling ProcessReady tells GameLift this game server is ready to receive incoming game sessions! var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters); if (processReadyOutcome.Success) { print("ProcessReady success."); } else { print("ProcessReady failure : " + processReadyOutcome.Error.ToString()); } } else { print("InitSDK failure : " + initSDKOutcome.Error.ToString()); } }
// Ends the game session for all and disconnects the players public void TerminateGameSession() { System.Console.WriteLine("Terminating Game Session"); GameObject.FindObjectOfType <Server>().DisconnectAll(); GameLiftServerAPI.TerminateGameSession(); this.gameStarted = false; }
private void OnDisconnectedEvent(NetPeer peer, DisconnectInfo info) { var pid = _playerEndPoints.Get(peer.EndPoint); if (!string.IsNullOrEmpty(pid)) { GameLiftServerAPI.RemovePlayerSession(pid); _logger.InfoFormat("remove player session: {0}", pid); _playerEndPoints.Delete(peer.EndPoint); } _peerList.Delete(peer.EndPoint); Console.WriteLine("disconnected: {0}, {1}", peer.EndPoint, info.Reason); if (!_peerList.IsEmpty()) { var json = CreateAdminMessage($"[{peer.EndPoint}]さんが抜けました").Serialize(); var w = new NetDataWriter(); _peerList.ForEach(p => { w.Reset(); w.Put(json); p.Send(w, DeliveryMethod.ReliableOrdered); }); return; } // 全員セッションから抜けたら終了する GameLiftServerAPI.TerminateGameSession(); _logger.InfoFormat("terminate game session: {0}", _session.GameSessionId); }
// Called from MLAPI on client disconnect // Called on MLAPI connection exception public void DisconnectPlayer(ulong clientId) { // if player slots never re-open, just skip this entire thing. try { var playerSessionId = playerSessions[clientId]; try { //Notifies the GameLift service that a player with the specified player session ID has disconnected //from the server process. In response, GameLift changes the player slot to available, //which allows it to be assigned to a new player. var outcome = GameLiftServerAPI.RemovePlayerSession(playerSessionId); GameLiftServerAPI.ProcessEnding(); // For now, killing game session on player leaving. Debug.Log(outcome.Success ? ":) PLAYER SESSION REMOVED" : $":( PLAYER SESSION REMOVE FAILED. RemovePlayerSession() returned {outcome.Error}"); } catch (Exception e) { Debug.Log($":( PLAYER SESSION REMOVE FAILED. RemovePlayerSession() exception\n{e.Message}"); throw; } playerSessions.Remove(clientId); } catch (KeyNotFoundException e) { Debug.Log($":( INVALID PLAYER SESSION. Exception \n{e.Message}"); throw; // should never happen } }
private void ProcessReady() { //Set the port that your game service is listening on for incoming player connections //In this example, the port is hardcoded for simplicity. Active games //that are on the same instance must have unique ports. const int listeningPort = 7777; // TODO: port picking logic? //Here, the game server tells GameLift what set of files to upload when the game session ends. //GameLift uploads everything specified here for the developers to fetch later. // must be different for each server if multiple servers on instance var logParameters = new LogParameters(new List <string> { "/local/game/myserver.log" }); var processParameters = new ProcessParameters( OnStartGameSession, OnProcessTerminate, OnHealthCheckDelegate, listeningPort, logParameters); //Notifies the GameLift service that the server process is ready to host game sessions. //Call this method after successfully invoking InitSDK() and completing setup tasks that are required //before the server process can host a game session. This method should be called only once per process. //Calling ProcessReady tells GameLift this game server is ready to receive incoming game sessions! var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters); Debug.Log(processReadyOutcome.Success ? "ProcessReady success." : $"ProcessReady failure : {processReadyOutcome.Error}"); }
private void InitializeServerProcess(int listeningPort) { //InitSDK will establish a local connection with GameLift's agent to enable further communication. var initSDKOutcome = GameLiftServerAPI.InitSDK(); if (initSDKOutcome.Success) { ProcessParameters processParameters = new ProcessParameters( (gameSession) => { //When a game session is created, GameLift sends an activation request to the game server and passes along the game session object containing game properties and other settings. //Here is where a game server should take action based on the game session object. //Once the game server is ready to receive incoming player connections, it should invoke GameLiftServerAPI.ActivateGameSession() GameLiftServerAPI.ActivateGameSession(); }, (updateGameSession) => { //When a game session is updated (e.g. by FlexMatch backfill), GameLiftsends a request to the game //server containing the updated game session object. The game server can then examine the provided //matchmakerData and handle new incoming players appropriately. //updateReason is the reason this update is being supplied. }, () => { //OnProcessTerminate callback. GameLift will invoke this callback before shutting down an instance hosting this game server. //It gives this game server a chance to save its state, communicate with services, etc., before being shut down. //In this case, we simply tell GameLift we are indeed going to shutdown. GameLiftServerAPI.ProcessEnding(); }, () => { //This is the HealthCheck callback. //GameLift will invoke this callback every 60 seconds or so. //Here, a game server might want to check the health of dependencies and such. //Simply return true if healthy, false otherwise. //The game server has 60 seconds to respond with its health status. GameLift will default to 'false' if the game server doesn't respond in time. //In this case, we're always healthy! return(true); }, listeningPort, //This game server tells GameLift that it will listen on port 7777 for incoming player connections. new LogParameters(new List <string>() { //Here, the game server tells GameLift what set of files to upload when the game session ends. //GameLift will upload everything specified here for the developers to fetch later. "/local/game/logs/myserver.log" })); //Calling ProcessReady tells GameLift this game server is ready to receive incoming game sessions! var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters); if (processReadyOutcome.Success) { print("ProcessReady success."); } else { print("ProcessReady failure : " + processReadyOutcome.Error.ToString()); } } else { print("InitSDK failure : " + initSDKOutcome.Error.ToString()); } }
private void OnApplicationQuit() { if (isHeadlessServer) { TerminateSession(); GameLiftServerAPI.Destroy(); } }
void Start() { LogOutcome("init", GameLiftServerAPI.InitSDK()); var logParams = new LogParameters(new List <string>()); var parameters = new ProcessParameters(OnStartGameSession, OnUpdateGameSession, OnProcessTerminated, OnHealthCheck, 1900, logParams); LogOutcome("ready", GameLiftServerAPI.ProcessReady(parameters)); }
void OnGameSession(GameSession gameSession) { // When a game session is created, GameLift sends an activation request to the game server and passes along // the game session object containing game properties and other settings. Here is where a game server should // take action based on the game session object. Once the game server is ready to receive incoming player // connections, it should invoke GameLiftServerAPI.ActivateGameSession() Debug.Log("ActivateGameSession"); GameLiftServerAPI.ActivateGameSession(); }
void OnProcessTerminate() { // game-specific tasks required to gracefully shut down a game session, // such as notifying players, preserving game state data, and other cleanup var ProcessEndingOutcome = GameLiftServerAPI.ProcessEnding(); GameLiftServerAPI.Destroy(); this.running = false; }
public int Run() { _logger.Info("call InitSDK"); var init = new GenericOutcome { Success = false }; for (var i = 0; i < 10; i++) { init = GameLiftServerAPI.InitSDK(); if (init.Success) { break; } _logger.ErrorFormat("init error: {0}", init.Error); Thread.Sleep(1000 * i + 1); } if (!init.Success) { _logger.ErrorFormat("cannot initialize GameLift Server SDK"); return(1); } _logger.Info("initialize GameLift Server SDK"); var server = ListenServer(); if (!server.IsRunning) { _logger.ErrorFormat("cannot launch server"); return(2); } var listenPort = server.LocalPort; _logger.InfoFormat("listen on: {0}", listenPort); GlobalContext.Properties["ListenPort"] = listenPort; if (!ProcessReady(listenPort, out var err)) { _logger.ErrorFormat("cannot ready to process: {0}", err); return(3); } while (_isRunning) { server.PollEvents(); Thread.Sleep(15); } _logger.InfoFormat("process ending: {0}", listenPort); ProcessEnding(); server.Stop(); return(0); }
public bool GameLiftStart(int listenPort) { //Debug.Log("GameLift Start with Port:" + listenPort); LogModule.WriteToLogFile("[GameLift] GameLift Start with Port:" + listenPort); var initSDKOutcome = GameLiftServerAPI.InitSDK(); if (initSDKOutcome.Success) { ProcessParameters processParameters = new ProcessParameters( (gameSession) => { //OnStartGameSession Callback LogModule.WriteToLogFile("[GameLift] OnStartGameSession with Parameter=" + gameSession); GameLiftServerAPI.ActivateGameSession(); }, (gameSession) => { //OnUpdateGameSession Callback //You can implement custom Match update logics using Backfill Ticket, UpdateReason, GameSession data. LogModule.WriteToLogFile("[GameLift] OnUpdateGameSession with Backfill Ticket=" + gameSession.BackfillTicketId + ", UpdateReason=" + gameSession.UpdateReason); }, () => { //OnProcessTerminate Callback LogModule.WriteToLogFile("[GameLift] ProcessEnding"); GameLiftServerAPI.ProcessEnding(); }, () => { //OnHealthCheck Callback return(true); }, listenPort, new LogParameters(new List <string>() { "./local/game/logs/myserver.log" //"C:\\game\\myserver.log" } )); var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters); if (processReadyOutcome.Success) { LogModule.WriteToLogFile("[GameLift] ProcessReady Success"); return(true); } else { LogModule.WriteToLogFile("[GameLift] ProcessReady Failure : " + processReadyOutcome.Error.ToString()); return(false); } } else { LogModule.WriteToLogFile("[GameLift] InitSDK failure : " + initSDKOutcome.Error.ToString()); return(false); } }
private void OnProcessTerminate() { //OnProcessTerminate callback. GameLift invokes this callback before shutting down //an instance hosting this game server. It gives this game server a chance to save //its state, communicate with services, etc., before being shut down. //In this case, we simply tell GameLift we are indeed going to shut down. Debug.Log(":| GAMELIFT PROCESS TERMINATION REQUESTED (OK BYE)"); GameLiftServerAPI.ProcessEnding(); }
private void HandlePlayerExit(string playerSessionId, int remaining) { LogOutcome("player term", GameLiftServerAPI.RemovePlayerSession(playerSessionId)); if (remaining == 0) { LogOutcome("game term", GameLiftServerAPI.TerminateGameSession()); LogOutcome("ending", GameLiftServerAPI.ProcessEnding()); Application.Quit(0); } }
private static void OnAcceptPlayerSession() // (NetworkMessage netMsg) { // Messages.AcceptPlayerSessionMessage msg = netMsg.ReadMessage<Messages.AcceptPlayerSessionMessage>(); GenericOutcome outcome = GameLiftServerAPI.AcceptPlayerSession(""); // msg.playerSessionId); if (!outcome.Success) { log.Error(outcome); return; } }
private static void OnGameSession(GameSession gameSession) { log.ConfigureNewGame(gameSession.GameSessionId); appgame = new Game(); string boardFile = "8 5\nA W W W W W W a\nB W W W W W W b\nW P W W W W p W\nC W W W W W W c\nD W W W W W W d"; appgame.board = new Map(boardFile); appgame.gameSessionId = gameSession.GameSessionId; gameSessionId = gameSession.GameSessionId; GameLiftServerAPI.ActivateGameSession(); }
private void SetupServerAndGamelift() { // start the unet server networkPort = LISTEN_PORT; StartServer(); print($"Server listening on port {networkPort}"); // initialize GameLift print("Starting GameLift initialization."); var initSDKOutcome = GameLiftServerAPI.InitSDK(); if (initSDKOutcome.Success) { isGameliftServer = true; var processParams = new ProcessParameters( (gameSession) => { // onStartGameSession callback GameLiftServerAPI.ActivateGameSession(); }, (updateGameSession) => { }, () => { // onProcessTerminate callback GameLiftServerAPI.ProcessEnding(); }, () => { // healthCheck callback return(true); }, LISTEN_PORT, new LogParameters(new List <string>() { "/local/game/logs/myserver.log" }) ); var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParams); if (processReadyOutcome.Success) { print("GameLift process ready."); } else { print($"GameLift: Process ready failure - {processReadyOutcome.Error.ToString()}."); } } else { print($"GameLift: InitSDK failure - {initSDKOutcome.Error.ToString()}."); } }
// This is an example of a simple integration with GameLift server SDK that will make game server processes go active on GameLift! public void Start() { //InitSDK will establish a local connection with GameLift's agent to enable further communication. var initSDKOutcome = GameLiftServerAPI.InitSDK(); _tcpServerPort = UnityEngine.Random.Range(7000, 8000); Debug.Log("TCP Port: " + _tcpServerPort); if (initSDKOutcome.Success) { ProcessParameters processParameters = new ProcessParameters( this.OnGameSession, this.OnGameSessionUpdate, this.OnProcessTerminate, this.OnHealthCheck, _tcpServerPort, // This game server tells GameLift the port it will listen on for incoming player connections. new LogParameters(new List <string>() { // Here, the game server tells GameLift what set of files to upload when the game session ends. // GameLift will upload everything specified here for the developers to fetch later. // When -isProd is NOT set, use a path relevant for local testing Startup.IsArgFlagPresent("-isProd") ? "/local/game/logs/server.log" : "~/Library/Logs/Unity/server.log" } )); // Calling ProcessReady tells GameLift this game server is ready to receive incoming game sessions! var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters); if (processReadyOutcome.Success) { print("ProcessReady success."); _server = GetComponent <BADNetworkServer>(); if (_server != null) { Debug.Log("BADNetworkServer is good."); _server.StartTCPServer(_tcpServerPort); } else { Debug.Log("BADNetworkServer is null."); } } else { print("ProcessReady failure : " + processReadyOutcome.Error.ToString()); } } else { print("InitSDK failure : " + initSDKOutcome.Error.ToString()); } }
// should be called when the server determines the game is over // and needs to signal Gamelift to terminate this instance public void TerminateSession() { Debug.Log("** TerminateSession Requested **"); if (isGameliftServer) { GameLiftServerAPI.TerminateGameSession(); GameLiftServerAPI.ProcessEnding(); } Debug.Log("** Process Exit **"); Application.Quit(); }
public void Start() { // Use command line port if possible, otherwise use default (hard coded port) string[] args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length - 1; i++) { int value = 0; if (args[i] != "-port") { continue; } if (!int.TryParse(args[i + 1], out value)) { continue; } if (value < 1000 || value >= 65536) { continue; } port = value; Debug.Log(":) LISTEN PORT " + port + " FOUND ON COMMAND LINE"); break; } string sdkVersion = GameLiftServerAPI.GetSdkVersion().Result; Debug.Log(":) SDK VERSION: " + sdkVersion); try { var initOutcome = GameLiftServerAPI.InitSDK(); if (initOutcome.Success) { Debug.Log(":) SERVER IS IN A GAMELIFT FLEET"); ProcessReady(); } else { if (gl != null) { gl.gameliftStatus = false; } Debug.Log(":( SERVER NOT IN A FLEET. GameLiftServerAPI.InitSDK() returned " + Environment.NewLine + initOutcome.Error.ErrorMessage); } } catch (Exception e) { Debug.Log(":( SERVER NOT IN A FLEET. GameLiftServerAPI.InitSDK() exception " + Environment.NewLine + e.Message); } }
private async void ActivateSession(GameSession gameSession) { try { Debug.Log("server start game session: " + gameSession.GameSessionId); server = new DemoServer(); await server.StartNetworked(AcceptPlayer, HandlePlayerExit, this, settings); LogOutcome("activate", GameLiftServerAPI.ActivateGameSession()); } catch (Exception e) { Debug.LogError("Exception on server update"); Debug.LogError(e); } }
public void EndProcess() { var processEndingOutcome = GameLiftServerAPI.ProcessEnding(); if (processEndingOutcome.Success) { LogModule.WriteToLogFile("[GameLift] End GameLift Server Process"); } else { LogModule.WriteToLogFile("[GameLift] Process Ending Failed. Result : " + processEndingOutcome.Error.ToString()); } }
public void RemovePlayer(string playerSessionId) { var removePlayerSessionOutcome = GameLiftServerAPI.RemovePlayerSession(playerSessionId); if (removePlayerSessionOutcome.Success) { LogModule.WriteToLogFile("[GameLift] Remove Player Session Success : " + playerSessionId); } else { LogModule.WriteToLogFile("[GameLift] Remove Player Session Failed. Result : " + removePlayerSessionOutcome.Error.ToString()); } }
void OnApplicationQuit() { if (started == true) { GameLiftServerAPI.Destroy(); } //Make sure to call GameLiftServerAPI.Destroy() when the application quits. //This resets the local connection with GameLift's agent. //bool headless = IsHeadlessMode(); //if (headless == true || StartEvenIfNotHeadless) //{ // GameLiftServerAPI.Destroy(); // } }
public bool AcceptPlayer(string playerSessionId) { var acceptPlayerSessionOutcome = GameLiftServerAPI.AcceptPlayerSession(playerSessionId); if (acceptPlayerSessionOutcome.Success) { LogModule.WriteToLogFile("[GameLift] Player Session Validated"); return(true); } else { LogModule.WriteToLogFile("[GameLift] Player Session Rejected. AcceptPlayerSession Result : " + acceptPlayerSessionOutcome.Error.ToString()); return(false); } }