コード例 #1
0
    public void CreateGameLiftClient()
    {
        var config = new AmazonGameLiftConfig();

        config.RegionEndpoint = Amazon.RegionEndpoint.APNortheast1;
        Debug.Log("GL372");
        try
        {
            CredentialProfile profile = null;
            var nscf = new SharedCredentialsFile();
            nscf.TryGetProfile(profileName, out profile);
            AWSCredentials credentials = profile.GetAWSCredentials(null);
            Debug.Log("demo-gamelift-unity profile GL376");
            aglc = new AmazonGameLiftClient(credentials, config);
            Debug.Log("GL378");
        }
        catch (AmazonServiceException)
        {
            Debug.Log("regular profile search GL382");
            try
            {
                aglc = new AmazonGameLiftClient(config);
            }
            catch (AmazonServiceException e)
            {
                Debug.Log("AWS Credentials not found. Cannot connect to GameLift. Start application with -credentials <file> flag where credentials are the credentials.csv or accessKeys.csv file containing the access and secret key. GL390");
                Debug.Log(e.Message);
            }
        }
    }
コード例 #2
0
        static async Task <string> CreateBuild(string name, string version, Amazon.GameLift.Model.S3Location s3Location)
        {
            using (var aglc = new AmazonGameLiftClient(new AmazonGameLiftConfig
            {
                RegionEndpoint = region
            }))
            {
                try
                {
                    CreateBuildResponse cbres = await aglc.CreateBuildAsync(new CreateBuildRequest
                    {
                        Name            = name,
                        Version         = version,
                        StorageLocation = s3Location
                    });

                    return(cbres.Build.BuildId);
                }
                catch (AmazonGameLiftException glException)
                {
                    Console.WriteLine(glException.Message, glException.InnerException);
                    throw;
                }
            }
        }
コード例 #3
0
ファイル: Client.cs プロジェクト: adalves/pong-gamelift-godot
    /// <summary>
    /// GameLift client
    /// </summary>
    public void SearchGameSessions()
    {
        GD.Print("starting search function");

        BasicAWSCredentials credentials = new BasicAWSCredentials("", "");

        gameLiftClient = new AmazonGameLiftClient(credentials, Amazon.RegionEndpoint.SAEast1);

        SearchGameSessionsRequest request = new SearchGameSessionsRequest()
        {
            FilterExpression = "hasAvailablePlayerSessions=true",
            FleetId          = PongServer
        };

        try
        {
            SearchGameSessionsResponse activeSessions = gameLiftClient.SearchGameSessions(request);
            List <GameSession>         sessions       = activeSessions.GameSessions;
            if (sessions.Count == 0)
            {
                CreateSession();
            }
            else
            {
                ConnectToSession(sessions[0]);
            }
        }
        catch (Exception e)
        {
            GD.Print(e);
        }
    }
コード例 #4
0
    private void Update()
    {
        // Create TCP server if we received port already
        if (Server.port > 0 && this.server == null)
        {
            Console.WriteLine("Port received, create network server");
            this.server = new NetworkServer(this);
        }

        // Register to FleetIQ if we have all the needed info and not registered yet
        if (!registeredToFleetIQ)
        {
            if (this.taskDataArnWithContainer != null && this.publicIP != null && this.instanceId != null)
            {
                Console.WriteLine("Registering to FleetIQ");
                var gameLiftConfig = new AmazonGameLiftConfig {
                    RegionEndpoint = this.regionEndpoint
                };
                var gameLiftClient            = new AmazonGameLiftClient(gameLiftConfig);
                var registerGameServerRequest = new RegisterGameServerRequest();
                registerGameServerRequest.GameServerGroupName = Server.fleetIqGameServerGroup;
                registerGameServerRequest.InstanceId          = this.instanceId;
                registerGameServerRequest.ConnectionInfo      = this.publicIP + ":" + Server.port;
                registerGameServerRequest.GameServerId        = this.gameServerId;
                registerGameServerRequest.GameServerData      = "{\"gametype\": \"normal\"}";
                var response = gameLiftClient.RegisterGameServerAsync(registerGameServerRequest);
                response.Wait();
                Console.WriteLine("Response HTTP code: " + response.Result.HttpStatusCode.ToString());
                Console.WriteLine("Response game server: " + response.Result.GameServer.GameServerData.ToString());
                Console.WriteLine("RegistrationRequest Sent!");

                this.registeredToFleetIQ = true;
            }
        }
    }
コード例 #5
0
 public Amazon.GameLift.Model.GameSession SearchGameSessions(AmazonGameLiftClient aglc)
 {
     try
     {
         var sgsreq = new Amazon.GameLift.Model.SearchGameSessionsRequest();
         sgsreq.AliasId          = aliasId;                           // only our game
         sgsreq.FilterExpression = "hasAvailablePlayerSessions=true"; // only ones we can join
         sgsreq.SortExpression   = "creationTimeMillis ASC";          // return oldest first
         sgsreq.Limit            = 1;                                 // only one session even if there are other valid ones
         Amazon.GameLift.Model.SearchGameSessionsResponse sgsres = aglc.SearchGameSessions(sgsreq);
         Debug.Log((int)sgsres.HttpStatusCode + " GAME SESSION SEARCH FOUND " + sgsres.GameSessions.Count + " SESSIONS (on " + aliasId + ")");
         if (sgsres.GameSessions.Count > 0)
         {
             return(sgsres.GameSessions[0]);
         }
         return(null);
     }
     catch (Amazon.GameLift.Model.InvalidRequestException e)
     {
         // EXCEPTION HERE? Your alias does not point to a valid fleet, possibly.
         Debug.Log(e.StatusCode.ToString() + " :( SEARCHGAMESESSIONS FAILED. InvalidRequestException " + e.Message +
                   Environment.NewLine + "Game alias " + aliasId + " may not point to a valid fleet" + Environment.NewLine);
         return(null);
     }
 }
コード例 #6
0
    public void UpdateFleetIQ(bool serverTerminated = false)
    {
        // Only update if we're ready
        if (this.server.IsReady())
        {
            Console.WriteLine("Server Ready, updating to FleetIQ");

            var utilizationStatus = GameServerUtilizationStatus.AVAILABLE;

            // If we have a player connected, we're utilized (backend has claimed this game server for 2 players)
            if (this.server.GetPlayerCount() > 0)
            {
                utilizationStatus = GameServerUtilizationStatus.UTILIZED;
            }

            var gameLiftConfig = new AmazonGameLiftConfig {
                RegionEndpoint = this.regionEndpoint
            };
            var gameLiftClient          = new AmazonGameLiftClient(gameLiftConfig);
            var updateGameServerRequest = new UpdateGameServerRequest();
            updateGameServerRequest.GameServerGroupName = Server.fleetIqGameServerGroup;
            updateGameServerRequest.GameServerId        = this.gameServerId;
            updateGameServerRequest.HealthCheck         = GameServerHealthCheck.HEALTHY;
            updateGameServerRequest.UtilizationStatus   = utilizationStatus;

            gameLiftClient.UpdateGameServerAsync(updateGameServerRequest);

            Console.WriteLine("FleetIQ Updat sent!");
        }
    }
コード例 #7
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonGameLiftConfig config = new AmazonGameLiftConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonGameLiftClient client = new AmazonGameLiftClient(creds, config);

            ListBuildsResponse resp = new ListBuildsResponse();

            do
            {
                ListBuildsRequest req = new ListBuildsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    Limit = maxItems
                };

                resp = client.ListBuilds(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Builds)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
コード例 #8
0
        public void UseLocalServer()
        {
            var conf = new AmazonGameLiftConfig {
                ServiceURL = "http://localhost:9080"
            };

            _glClient = new AmazonGameLiftClient(conf);
        }
コード例 #9
0
        public async Task <APIGatewayProxyResponse> Post(APIGatewayProxyRequest request, ILambdaContext context)
        {
            JoinGameRequest      input        = JsonSerializer.Deserialize <JoinGameRequest>(request.Body);
            AmazonGameLiftClient amazonClient = new AmazonGameLiftClient(Amazon.RegionEndpoint.USEast1);

            ListAliasesRequest aliasReq = new ListAliasesRequest();

            aliasReq.Name = "WarshopServer";
            Alias aliasRes = (await amazonClient.ListAliasesAsync(aliasReq)).Aliases[0];
            DescribeAliasRequest describeAliasReq = new DescribeAliasRequest();

            describeAliasReq.AliasId = aliasRes.AliasId;
            string fleetId = (await amazonClient.DescribeAliasAsync(describeAliasReq.AliasId)).Alias.RoutingStrategy.FleetId;

            DescribeGameSessionsResponse gameSession = await amazonClient.DescribeGameSessionsAsync(new DescribeGameSessionsRequest()
            {
                GameSessionId = input.gameSessionId
            });

            bool   IsPrivate = gameSession.GameSessions[0].GameProperties.Find((GameProperty gp) => gp.Key.Equals("IsPrivate")).Value.Equals("True");
            string Password  = IsPrivate ? gameSession.GameSessions[0].GameProperties.Find((GameProperty gp) => gp.Key.Equals("Password")).Value : "";

            if (!IsPrivate || input.password.Equals(Password))
            {
                CreatePlayerSessionRequest playerSessionRequest = new CreatePlayerSessionRequest();
                playerSessionRequest.PlayerId      = input.playerId;
                playerSessionRequest.GameSessionId = input.gameSessionId;
                CreatePlayerSessionResponse playerSessionResponse = amazonClient.CreatePlayerSessionAsync(playerSessionRequest).Result;
                JoinGameResponse            response = new JoinGameResponse
                {
                    playerSessionId = playerSessionResponse.PlayerSession.PlayerSessionId,
                    ipAddress       = playerSessionResponse.PlayerSession.IpAddress,
                    port            = playerSessionResponse.PlayerSession.Port
                };

                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body = JsonSerializer.Serialize(response),
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                });
            }
            else
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = "Incorrect password for private game",
                });
            }
        }
コード例 #10
0
        public Client()
        {
            var conf = new AmazonGameLiftConfig {
                RegionEndpoint = RegionEndpoint.APNortheast1
            };

            _glClient = new AmazonGameLiftClient(conf);
            Console.CancelKeyPress += (sender, args) =>
            {
                args.Cancel = true;
                _isRunning  = false;
            };
        }
コード例 #11
0
        protected IAmazonGameLift CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonGameLiftConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonGameLiftClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
コード例 #12
0
    // Ends the game session for all and disconnects the players
    public void TerminateGameSession()
    {
        Console.WriteLine("Terminating session and Task");
        // Let FleetIQ know we are done
        var gameLiftConfig = new AmazonGameLiftConfig {
            RegionEndpoint = this.server.regionEndpoint
        };
        var gameLiftClient = new AmazonGameLiftClient(gameLiftConfig);
        var deregisterGameServerRequest = new DeregisterGameServerRequest();

        deregisterGameServerRequest.GameServerGroupName = Server.fleetIqGameServerGroup;
        deregisterGameServerRequest.GameServerId        = this.server.GetGameServerId();
        var response = gameLiftClient.DeregisterGameServerAsync(deregisterGameServerRequest);

        response.Wait();
        Console.WriteLine("Deregistered from FleetIQ, terminate Task...");
        Application.Quit();
    }
コード例 #13
0
 public Amazon.GameLift.Model.PlayerSession CreatePlayerSession(AmazonGameLiftClient aglc, Amazon.GameLift.Model.GameSession gsession)
 {
     try
     {
         var cpsreq = new Amazon.GameLift.Model.CreatePlayerSessionRequest();
         cpsreq.GameSessionId = gsession.GameSessionId;
         cpsreq.PlayerId      = playerId;
         Amazon.GameLift.Model.CreatePlayerSessionResponse cpsres = aglc.CreatePlayerSession(cpsreq);
         string psid = cpsres.PlayerSession != null ? cpsres.PlayerSession.PlayerSessionId : "N/A";
         Debug.Log((int)cpsres.HttpStatusCode + " PLAYER SESSION CREATED: " + psid);
         return(cpsres.PlayerSession);
     }
     catch (Amazon.GameLift.Model.InvalidGameSessionStatusException e)
     {
         Debug.Log(e.StatusCode.ToString() + " InvalidGameSessionStatusException: " + e.Message);
         return(null);
     }
 }
コード例 #14
0
        public async Task <APIGatewayProxyResponse> Get(ILambdaContext context)
        {
            AmazonGameLiftClient amazonClient = new AmazonGameLiftClient(Amazon.RegionEndpoint.USEast1);

            ListAliasesRequest aliasReq = new ListAliasesRequest();

            aliasReq.Name = "WarshopServer";
            Alias aliasRes = (await amazonClient.ListAliasesAsync(aliasReq)).Aliases[0];
            DescribeAliasRequest describeAliasReq = new DescribeAliasRequest();

            describeAliasReq.AliasId = aliasRes.AliasId;
            string fleetId = (await amazonClient.DescribeAliasAsync(describeAliasReq.AliasId)).Alias.RoutingStrategy.FleetId;

            DescribeGameSessionsRequest describeReq = new DescribeGameSessionsRequest();

            describeReq.FleetId      = fleetId;
            describeReq.StatusFilter = GameSessionStatus.ACTIVE;
            DescribeGameSessionsResponse describeRes = await amazonClient.DescribeGameSessionsAsync(describeReq);

            List <GameView> gameViews = describeRes.GameSessions
                                        .FindAll((GameSession g) => g.CurrentPlayerSessionCount < g.MaximumPlayerSessionCount)
                                        .ConvertAll((GameSession g) => new GameView()
            {
                gameSessionId = g.GameSessionId,
                creatorId     = g.CreatorId,
                isPrivate     = true.ToString() == g.GameProperties.Find((GameProperty gp) => gp.Key.Equals("IsPrivate")).Value
            });

            GetGamesResponse response = new GetGamesResponse()
            {
                gameViews = gameViews.ToArray()
            };

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = JsonSerializer.Serialize(response),
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            });
        }
コード例 #15
0
        private static async Task <string> UpdateAlias(string aliasUpdate, string fleetId)
        {
            var config = new AmazonGameLiftConfig();

            config.RegionEndpoint = region;
            using (AmazonGameLiftClient aglc = new AmazonGameLiftClient(config))
            {
                // create a new alias
                var uareq = new Amazon.GameLift.Model.UpdateAliasRequest();
                uareq.AliasId         = aliasUpdate;
                uareq.RoutingStrategy = new RoutingStrategy
                {
                    Type    = RoutingStrategyType.SIMPLE,
                    FleetId = fleetId,
                    Message = ""
                };
                Amazon.GameLift.Model.UpdateAliasResponse cares = await aglc.UpdateAliasAsync(uareq);

                return(cares.Alias.AliasId);
            }
        }
コード例 #16
0
        static async Task <string> CreateAlias(string name, string fleetId)
        {
            var config = new AmazonGameLiftConfig();

            config.RegionEndpoint = region;
            using (AmazonGameLiftClient aglc = new AmazonGameLiftClient(config))
            {
                // create fleet
                var careq = new Amazon.GameLift.Model.CreateAliasRequest();
                careq.Name            = name;
                careq.Description     = "Alias to direct traffic to " + fleetId;
                careq.RoutingStrategy = new RoutingStrategy
                {
                    Type    = RoutingStrategyType.SIMPLE,
                    FleetId = fleetId,
                    Message = ""
                };
                Amazon.GameLift.Model.CreateAliasResponse cares = await aglc.CreateAliasAsync(careq);

                return(cares.Alias.AliasId);
            }
        }
コード例 #17
0
    private void CreateGameLiftClient()
    {
        Debug.Log("CreateGameLiftClient");

        CognitoAWSCredentials credentials = new CognitoAWSCredentials(
            CognitoIdentityPool,
            RegionEndpoint.USEast1
            );

        if (IsArgFlagPresent(IsProdArg))
        {
            _amazonGameLiftClient = new AmazonGameLiftClient(credentials, RegionEndpoint.USEast1);
        }
        else
        {
            // local testing
            // guide: https://docs.aws.amazon.com/gamelift/latest/developerguide/integration-testing-local.html
            AmazonGameLiftConfig amazonGameLiftConfig = new AmazonGameLiftConfig()
            {
                ServiceURL = "http://localhost:9080"
            };
            _amazonGameLiftClient = new AmazonGameLiftClient("asdfasdf", "asdf", amazonGameLiftConfig);
        }
    }
コード例 #18
0
    public void DoInitClient()
    {
        if (clientInit == true)
        {
            LogToMyConsoleMainThread("Client Already Initialized");
            return;
        }


        clientInit = true;
        UniqueID   = System.Guid.NewGuid().ToString();

        UnityInitializer.AttachToGameObject(gameObject);

        AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;

        AmazonGameLiftConfig gameLiftConfig = new AmazonGameLiftConfig();

        if (localMode == false)
        {
            gameLiftConfig.RegionEndpoint = RegionEndpoint.USWest2;
        }
        else
        {
            gameLiftConfig.ServiceURL = "http://localhost:9080";
        }



        m_Client = new AmazonGameLiftClient(
            staticData.awsAccessKeyId,
            staticData.awsSecretAccessKey,
            gameLiftConfig);

        LogToMyConsoleMainThread("Client Initialized");
    }
コード例 #19
0
 public Amazon.GameLift.Model.GameSession CreateGameSession(AmazonGameLiftClient aglc)
 {
     try
     {
         var cgsreq = new Amazon.GameLift.Model.CreateGameSessionRequest();
         cgsreq.AliasId   = aliasId;
         cgsreq.CreatorId = playerId;
         cgsreq.MaximumPlayerSessionCount = 4;
         Amazon.GameLift.Model.CreateGameSessionResponse cgsres = aglc.CreateGameSession(cgsreq);
         string gsid = cgsres.GameSession != null ? cgsres.GameSession.GameSessionId : "N/A";
         Debug.Log((int)cgsres.HttpStatusCode + " GAME SESSION CREATED: " + gsid);
         return(cgsres.GameSession);
     }
     catch (Amazon.GameLift.Model.FleetCapacityExceededException e)
     {
         Debug.Log(e.StatusCode.ToString() + " FleetCapacityExceededException: " + e.Message);
         return(null);
     }
     catch (Amazon.GameLift.Model.InvalidRequestException e)
     {
         Debug.Log(e.StatusCode.ToString() + " InvalidRequestException: " + e.Message);
         return(null);
     }
 }
コード例 #20
0
        public async Task <APIGatewayProxyResponse> Post(APIGatewayProxyRequest request, ILambdaContext context)
        {
            CreateGameRequest    body         = JsonSerializer.Deserialize <CreateGameRequest>(request.Body);
            AmazonGameLiftClient amazonClient = new AmazonGameLiftClient(Amazon.RegionEndpoint.USEast1);

            ListAliasesRequest aliasReq = new ListAliasesRequest();

            aliasReq.Name = "WarshopServer";
            Alias aliasRes = (await amazonClient.ListAliasesAsync(aliasReq)).Aliases[0];
            DescribeAliasRequest describeAliasReq = new DescribeAliasRequest();

            describeAliasReq.AliasId = aliasRes.AliasId;
            string fleetId = (await amazonClient.DescribeAliasAsync(describeAliasReq.AliasId)).Alias.RoutingStrategy.FleetId;

            CreateGameSessionRequest req = new CreateGameSessionRequest();

            req.MaximumPlayerSessionCount = 2;
            req.FleetId   = fleetId;
            req.CreatorId = body.playerId;
            req.GameProperties.Add(new GameProperty()
            {
                Key   = "IsPrivate",
                Value = body.isPrivate.ToString()
            });
            req.GameProperties.Add(new GameProperty()
            {
                Key   = "Password",
                Value = body.password == null ? "" : body.password
            });
            try
            {
                CreateGameSessionResponse res = await amazonClient.CreateGameSessionAsync(req);

                GameSession gameSession = res.GameSession;
                int         retries     = 0;
                while (gameSession.Status.Equals(GameSessionStatus.ACTIVATING) && retries < 100)
                {
                    DescribeGameSessionsRequest describeReq = new DescribeGameSessionsRequest();
                    describeReq.GameSessionId = res.GameSession.GameSessionId;
                    gameSession = (await amazonClient.DescribeGameSessionsAsync(describeReq)).GameSessions[0];
                    retries++;
                }

                CreatePlayerSessionRequest playerSessionRequest = new CreatePlayerSessionRequest();
                playerSessionRequest.PlayerId      = body.playerId;
                playerSessionRequest.GameSessionId = gameSession.GameSessionId;
                CreatePlayerSessionResponse playerSessionResponse = await amazonClient.CreatePlayerSessionAsync(playerSessionRequest);

                CreateGameResponse response = new CreateGameResponse {
                    playerSessionId = playerSessionResponse.PlayerSession.PlayerSessionId,
                    ipAddress       = playerSessionResponse.PlayerSession.IpAddress,
                    port            = playerSessionResponse.PlayerSession.Port
                };
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body = JsonSerializer.Serialize(response),
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                });
            }
            catch (NotFoundException e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.NotFound,
                    Body = "Your game is out of date! Download the newest version\n" + e.Message,
                });
            }
            catch (FleetCapacityExceededException e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Our game servers are too busy right now, come back later!\n" + e.Message,
                });
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "An unexpected error occurred! Please notify the developers.\n" + e.Message,
                });
            }
        }
コード例 #21
0
 public RoomMgr()
 {
     gameLiftClient = new AmazonGameLiftClient(accessKeyId, secretAccessKey, regionEndpoint);
 }
コード例 #22
0
    public GameLiftClient(GameLift _gl)
    {
        gl       = _gl;
        playerId = Guid.NewGuid().ToString();
        Credentials.Install();

        // Use command line alias if possible, otherwise use default (hard coded alias)
        string[] args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length - 1; i++)
        {
            if (args[i] != "--alias")
            {
                //Debug.Log(":( Unrecognized command line parameter: " + args[i] + " (consider --alias <aliasId>)" + Environment.NewLine);
                continue;
            }

            string pattern = @"alias-[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}";
            Match  m       = Regex.Match(args[i + 1], pattern);
            if (m.Success)
            {
                aliasId = m.Value;
                Debug.Log(":) ALIAS RECOGNIZED. Alias " + aliasId + " found on command line");
                break;
            }
        }

        // verify alias exists
        var config = new AmazonGameLiftConfig();

        config.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
        AmazonGameLiftClient aglc = null;
        AWSCredentials       credentials;

        var  chain        = new CredentialProfileStoreChain();
        bool profileFound = chain.TryGetAWSCredentials("demo-gamelift-unity", out credentials);

        if (profileFound)
        {
            Debug.Log("demo-gamelift-unity profile");
            aglc = new AmazonGameLiftClient(credentials, config);
        }
        else
        {
            Debug.Log("regular profile search");
            try
            {
                aglc = new AmazonGameLiftClient(config);
            }
            catch (AmazonServiceException e)
            {
                Debug.Log(e.Message);
                Debug.Log("AWS Credentials not found. Cannot connect to GameLift. Start application with -credentials <file> flag where credentials are the credentials.csv file containing the access and secret key.");
            }
        }
        if (aglc != null)
        {
            try
            {
                var dareq = new Amazon.GameLift.Model.DescribeAliasRequest();
                dareq.AliasId = aliasId;
                Amazon.GameLift.Model.DescribeAliasResponse dares = aglc.DescribeAlias(dareq);
                Amazon.GameLift.Model.Alias alias = dares.Alias;
                Debug.Log((int)dares.HttpStatusCode + " ALIAS NAME: " + alias.Name + " (" + aliasId + ")");
                if (alias.RoutingStrategy.Type == Amazon.GameLift.RoutingStrategyType.TERMINAL)
                {
                    Debug.Log("             (TERMINAL ALIAS)");
                }
            }
            catch (Exception e)
            {
                Debug.Log("AWS Credentials found but probably invalid. Check IAM permissions for the credentials.");
                Debug.Log(e.Message);
            }
            finally
            {
                aglc.Dispose();
            }
        }
    }
コード例 #23
0
        static async Task <string> CreateFleet(string name, string version, string buildId)
        {
            var config = new AmazonGameLiftConfig();

            config.RegionEndpoint = region;
            using (AmazonGameLiftClient aglc = new AmazonGameLiftClient(config))
            {
                // create launch configuration
                var serverProcess = new ServerProcess();
                serverProcess.ConcurrentExecutions = 1;
                serverProcess.LaunchPath           = @"C:\game\GameLiftUnity.exe"; // @"/local/game/ReproGLLinux.x86_64";
                serverProcess.Parameters           = "-batchmode -nographics";

                // create inbound IP permissions
                var permission1 = new IpPermission();
                permission1.FromPort = 1935;
                permission1.ToPort   = 1935;
                permission1.Protocol = IpProtocol.TCP;
                permission1.IpRange  = "0.0.0.0/0";

                // create inbound IP permissions
                var permission2 = new IpPermission();
                permission2.FromPort = 3389;
                permission2.ToPort   = 3389;
                permission2.Protocol = IpProtocol.TCP;
                permission2.IpRange  = "0.0.0.0/0";

                // create fleet
                var cfreq = new CreateFleetRequest();
                cfreq.Name            = name;
                cfreq.Description     = version;
                cfreq.BuildId         = buildId;
                cfreq.EC2InstanceType = EC2InstanceType.C4Large;
                cfreq.EC2InboundPermissions.Add(permission1);
                cfreq.EC2InboundPermissions.Add(permission2);
                cfreq.RuntimeConfiguration = new RuntimeConfiguration();
                cfreq.RuntimeConfiguration.ServerProcesses = new List <ServerProcess>();
                cfreq.RuntimeConfiguration.ServerProcesses.Add(serverProcess);
                cfreq.NewGameSessionProtectionPolicy = ProtectionPolicy.NoProtection;
                CreateFleetResponse cfres = await aglc.CreateFleetAsync(cfreq);

                // set fleet capacity
                var ufcreq = new UpdateFleetCapacityRequest();
                ufcreq.MinSize          = 0;
                ufcreq.DesiredInstances = 1;
                ufcreq.MaxSize          = 1;
                ufcreq.FleetId          = cfres.FleetAttributes.FleetId;
                UpdateFleetCapacityResponse ufcres = await aglc.UpdateFleetCapacityAsync(ufcreq);

                // set scaling rule (switch fleet off after 1 day of inactivity)
                // If [MetricName] is [ComparisonOperator] [Threshold] for [EvaluationPeriods] minutes, then [ScalingAdjustmentType] to/by [ScalingAdjustment].
                var pspreq = new PutScalingPolicyRequest();
                pspreq.Name                  = "Switch fleet off after 1 day of inactivity";
                pspreq.MetricName            = MetricName.ActiveGameSessions;
                pspreq.ComparisonOperator    = ComparisonOperatorType.LessThanOrEqualToThreshold;
                pspreq.Threshold             = 0.0;  // double (don't use int)
                pspreq.EvaluationPeriods     = 1435; // just under 1 day, 1435 appears to be the maximum permitted value now.
                pspreq.ScalingAdjustmentType = ScalingAdjustmentType.ExactCapacity;
                pspreq.ScalingAdjustment     = 0;
                pspreq.FleetId               = cfres.FleetAttributes.FleetId;
                PutScalingPolicyResponse pspres = await aglc.PutScalingPolicyAsync(pspreq);

                return(cfres.FleetAttributes.FleetId);
            }
        }
コード例 #24
0
    public void GetConnectionInfo(ref string ip, ref int port, ref string auth)
    {
        Debug.Log("GetConnectionInfo()");
        var config = new AmazonGameLiftConfig();

        config.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
        AmazonGameLiftClient aglc = null;
        AWSCredentials       credentials;
        var  chain        = new CredentialProfileStoreChain();
        bool profileFound = chain.TryGetAWSCredentials("demo-gamelift-unity", out credentials);

        if (profileFound)
        {
            Debug.Log("demo-gamelift-unity profile");
            aglc = new AmazonGameLiftClient(credentials, config);
        }
        else
        {
            Debug.Log("regular profile search");
            try
            {
                aglc = new AmazonGameLiftClient(config);
            }
            catch (AmazonServiceException e)
            {
                // search failed
                Debug.Log(e.Message);
                Debug.Log("AWS Credentials not found. Cannot connect to GameLift. Start application with -credentials <file> flag where credentials are the credentials.csv file containing the access and secret key.");
            }
        }
        if (aglc != null)
        {
            try
            {
                for (int retry = 0; retry < 4; retry++)
                {
                    Debug.Log("SearchGameSessions retry==" + retry);
                    Amazon.GameLift.Model.GameSession gsession = SearchGameSessions(aglc);
                    if (gsession != null)
                    {
                        Debug.Log("GameSession found " + gsession.GameSessionId);
                        Amazon.GameLift.Model.PlayerSession psession = CreatePlayerSession(aglc, gsession);
                        if (psession != null)
                        {
                            // created a player session in there
                            ip   = psession.IpAddress;
                            port = psession.Port;
                            auth = psession.PlayerSessionId;
                            Debug.Log("CLIENT CONNECT INFO: " + ip + ", " + port + ", " + auth);
                            if (gl.gamelogic != null)
                            {
                                gl.gamelogic.GameliftStatus = true;
                            }
                            aglc.Dispose();
                            return;
                        }

                        // player session creation failed (probably beaten to the session by another player)
                        retry = 0; // start over
                    }
                }

                // no game session, we should create one
                for (int retry = 0; retry < 4; retry++)
                {
                    Debug.Log("GameSession not found. CreateGameSession: retry==" + retry);
                    Amazon.GameLift.Model.GameSession gsession = CreateGameSession(aglc);
                    if (gsession != null)
                    {
                        for (int psretry = 0; psretry < 4; psretry++)
                        {
                            Debug.Log("CreatePlayerSession: retry==" + psretry);
                            psession = CreatePlayerSession(aglc, gsession);
                            if (psession != null)
                            {
                                // created a player session in there
                                ip   = psession.IpAddress;
                                port = psession.Port;
                                auth = psession.PlayerSessionId;
                                Debug.Log("CLIENT CONNECT INFO: " + ip + ", " + port + ", " + auth);
                                if (gl.gamelogic != null)
                                {
                                    gl.gamelogic.GameliftStatus = true;
                                }
                                aglc.Dispose();
                                return;
                            }
                        }

                        // player session creation failed (probably beaten to the session by another player)
                        retry = 0; // start over
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("AWS Credentials found but probably invalid. Check IAM permissions for the credentials.");
                Debug.Log(e.Message);
            }
            finally
            {
                aglc.Dispose();
            }
        }

        // something's not working. fall back to local client
        Debug.Log("CLIENT CONNECT INFO (LOCAL): " + ip + ", " + port + ", " + auth);
        if (gl.gamelogic != null)
        {
            gl.gamelogic.GameliftStatus = false;
        }
    }