Exemplo n.º 1
0
    /// <summary>
    /// Creates a build
    /// </summary>
    /// <returns>
    /// Boolean representing whether the call was successful or not
    /// </returns>
    public async Task <bool> CreateBuild(
        string strName,
        ContainerFlavor containerFlavor,
        List <AssetReferenceParams> lstGameAssets,
        List <GameCertificateReferenceParams> lstCertificates,
        List <Port> lstPorts,
        Dictionary <string, string> metaData,
        List <BuildRegionParams> lstRegions,
        int multiplayerServerCountPerVm,
        string strStartGameCommand,
        AzureVmSize VMSize
        )
    {
        // Create a build with the requested specificaitons
        CreateBuildWithManagedContainerRequest createRequest = new CreateBuildWithManagedContainerRequest()
        {
            BuildName                 = strName,
            ContainerFlavor           = containerFlavor,
            GameAssetReferences       = lstGameAssets,
            GameCertificateReferences = lstCertificates,
            Ports                         = lstPorts,
            Metadata                      = metaData,
            RegionConfigurations          = lstRegions,
            MultiplayerServerCountPerVm   = multiplayerServerCountPerVm,
            StartMultiplayerServerCommand = strStartGameCommand,
            VmSize                        = VMSize
        };

        var createResp = await PlayFabMultiplayerAPI.CreateBuildWithManagedContainerAsync(createRequest);

        bool hasError = CheckForError(createResp);

        if (hasError)
        {
            throw new Exception(String.Format("Create Build failed with error: {0}", createResp.Error.ErrorMessage));
        }

        return(!hasError);
    }
Exemplo n.º 2
0
 public void ListBuilds()
 {
     ShowLoader();
     PlayFabMultiplayerAPI.ListBuildSummaries(new ListBuildSummariesRequest {
     },
                                              result => {
         HideLoader();
         if (result.BuildSummaries.Count > 0)
         {
             EnumerateBuilds(result);
         }
         else
         {
             Inform("No servers were found.");
         }
         Debug.Log("Build summaries result: " + result.ToJson());
     },
                                              error => {
         Inform("Error: " + error.ErrorMessage);
         Debug.LogError("Build Summaries ERROR: " + error.GenerateErrorReport());
     });
 }
Exemplo n.º 3
0
        static async Task ListVirtualMachineSummaries()
        {
            var    req     = new PlayFab.MultiplayerModels.ListVirtualMachineSummariesRequest();
            string buildID = ReadBuildIDFromInput();
            var    regions = await GetRegions(buildID);

            Console.WriteLine($"Enter region (options are {string.Join(",", regions)})");
            string region = Console.ReadLine();

            req.Region  = region;
            req.BuildId = buildID;
            var res = await PlayFabMultiplayerAPI.ListVirtualMachineSummariesAsync(req);

            if (res.Error != null)
            {
                Console.WriteLine(res.Error.ErrorMessage);
            }
            else
            {
                PrettyPrintJson(res.Result);
            }
        }
Exemplo n.º 4
0
        static async Task RequestMultiplayerServer()
        {
            var req2 = new PlayFab.MultiplayerModels.RequestMultiplayerServerRequest();

            req2.BuildId = ReadBuildIDFromInput();
            var regions = await GetRegions(req2.BuildId);

            Console.WriteLine($"Enter region (options are {string.Join(",", regions)})");
            string region = Console.ReadLine();

            req2.PreferredRegions = new List <string>()
            {
                region
            };
            req2.SessionId = Guid.NewGuid().ToString();
            // Initial list of players (potentially matchmade) allowed to connect to the game.
            // This list is passed to the game server when requested (via GSDK) and can be used to validate players connecting to it.
            Console.WriteLine("Type initial players ID, Enter to confirm. Empty string when you're done");
            string id = Console.ReadLine();

            while (!string.IsNullOrEmpty(id))
            {
                req2.InitialPlayers ??= new List <string>();
                req2.InitialPlayers.Add(id.Trim());
                Console.WriteLine($"player with ID {id} was recorded, type the next one. Empty string when you're done");
                id = Console.ReadLine();
            }
            var res = await PlayFabMultiplayerAPI.RequestMultiplayerServerAsync(req2);

            if (res.Error != null)
            {
                Console.WriteLine(res.Error.ErrorMessage);
            }
            else
            {
                PrettyPrintJson(res.Result);
            }
        }
Exemplo n.º 5
0
    public void GetQoSServers()
    {
        ListQosServersRequest request = new ListQosServersRequest();

        PlayFabMultiplayerAPI.ListQosServers(request, ListQoSServersResponseSuccess, ListQoSServersResponseError, null, null);
    }
        public static async Task <RoomServerInfo> EnterRoom(CloudFunctionContext context, string roomId)
        {
            //// TODO [bgish]: Verify this is an actual room...
            //// TODO [bgish]: Verify this user has the right to enter this room...

            // Querying Title Data to figure out what server info we should be using
            var gameServerInfoKey = "GameServerInfo";

            var getTitleData = await global::PlayFab.PlayFabServerAPI.GetTitleDataAsync(new global::PlayFab.ServerModels.GetTitleDataRequest
            {
                Keys = new List <string> {
                    gameServerInfoKey
                },
                AuthenticationContext = context.TitleAuthenticationContext,
            });

            GameServerInfo gameServerInfo = JsonUtil.Deserialize <GameServerInfo>(getTitleData.Result.Data[gameServerInfoKey]);

            // Querying if the server info already exists
            RoomServerInfo serverInfo = GetServerInfoForRoom(roomId);

            if (serverInfo == null)
            {
                serverInfo = new RoomServerInfo
                {
                    RoomId    = roomId,
                    SessionId = Guid.NewGuid().ToString("D"),
                    BuildId   = gameServerInfo.BuildId,
                };

                if (AddServerInfoIfDoesNotExist(serverInfo))
                {
                    DateTime start = DateTime.Now;

                    // We were successful registering our ServerInfo, they we need to spin up an actual server and set that data too
                    var request = await PlayFabMultiplayerAPI.RequestMultiplayerServerAsync(new RequestMultiplayerServerRequest
                    {
                        SessionId             = serverInfo.SessionId,
                        BuildId               = serverInfo.BuildId,
                        PreferredRegions      = gameServerInfo.Regions,
                        AuthenticationContext = context.TitleAuthenticationContext,
                    });

                    DateTime end = DateTime.Now;

                    UnityEngine.Debug.Log($"RequestMultiplayerServerRequest Time = {end.Subtract(start).TotalMilliseconds}");

                    serverInfo.FQDN     = request.Result.FQDN;
                    serverInfo.Ports    = request.Result.Ports;
                    serverInfo.Region   = request.Result.Region;
                    serverInfo.ServerId = request.Result.ServerId;

                    if (serverInfo.SessionId != request.Result.SessionId)
                    {
                        UnityEngine.Debug.LogError($"Multiplayer Session Id Changed from {serverInfo.SessionId} to {request.Result.SessionId}");
                        serverInfo.SessionId = request.Result.SessionId;
                    }

                    UpdateServerInfo(serverInfo);

                    return(serverInfo);
                }
                else
                {
                    // NOTE [bgish]: This will fail if the winner has the RequestMultiplayerServerAsync fail due to lack of availability
                    // Someone beat us to the punch and added one before us, so lets poll till we get the server info
                    serverInfo = GetServerInfoForRoom(roomId);

                    int retryCount = 0;
                    while (string.IsNullOrEmpty(serverInfo?.FQDN))
                    {
                        await Task.Delay(100);

                        serverInfo = GetServerInfoForRoom(roomId);
                        retryCount++;

                        if (retryCount > 30)
                        {
                            throw new Exception("Retry Count Max Met!");
                        }
                    }

                    return(serverInfo);
                }
            }
            else
            {
                var getServerInfo = await PlayFabMultiplayerAPI.GetMultiplayerServerDetailsAsync(new GetMultiplayerServerDetailsRequest
                {
                    BuildId               = serverInfo.BuildId,
                    Region                = serverInfo.Region,
                    SessionId             = serverInfo.SessionId,
                    AuthenticationContext = context.TitleAuthenticationContext,
                });

                if (getServerInfo.Error == null)
                {
                    // If it didn't return an error, it should still be good
                    return(serverInfo);
                }
                else
                {
                    // We know this session is no longer valid, so remove it from the cache and get a new one
                    DeleteServerInfoIfDataHasntChanged(serverInfo.RoomId, serverInfo.SessionId, serverInfo.Region);
                    return(await EnterRoom(context, roomId));
                }
            }
        }
Exemplo n.º 7
0
    /// <summary>
    /// Retrieves a list of all available assets
    /// </summary>
    /// <returns>
    /// List of assets and their details
    /// </returns>
    public async Task <List <AssetSummary> > GetAllAssets()
    {
        var task = await PlayFabMultiplayerAPI.ListAssetSummariesAsync(null);

        return(task.Result.AssetSummaries);
    }
Exemplo n.º 8
0
    public void StartMatchmaking()
    {
        PlayfabUtils.OnSuccess(feedbackText, "Matchmaking in progress...");

        PlayFabMultiplayerAPI.ListQosServersForTitle(new ListQosServersForTitleRequest(), qosRes =>
        {
            var qosServer = qosRes.QosServers[0].ServerUrl;
            var qosRegion = qosRes.QosServers[0].Region;
            Debug.Log($"Pinging QoS Server {qosServer} at {qosRegion}");
            Debug.Log(qosRes.ToJson());

            var sw = System.Diagnostics.Stopwatch.StartNew();

            var udpPort = 5600;
            var done    = false;
            while (!done || udpPort > 5610)
            {
                try
                {
                    UdpClient client = new UdpClient(udpPort);
                    client.Connect(qosServer, 3075);
                    byte[] sendBytes = BitConverter.GetBytes(0xFFFF);
                    client.Send(sendBytes, sendBytes.Length);

                    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 3075);
                    byte[] receiveBytes       = client.Receive(ref remoteEndPoint);
                    client.Close();
                    done = true;
                }
                catch (Exception e)
                {
                    Debug.LogError($"[QoS Ping Error]: {e.Message}");
                    udpPort++;
                    Debug.Log($"Retrying with port {udpPort}");
                }
            }
            var pingTime = sw.ElapsedMilliseconds;
            Debug.Log($"Ping success with {pingTime}ms");
            if (udpPort > 5610)
            {
                StartMatchmaking();
                return;
            }

            var request = new CreateMatchmakingTicketRequest
            {
                Creator = new MatchmakingPlayer
                {
                    Entity = new PlayFab.MultiplayerModels.EntityKey
                    {
                        Id   = loginManager.playerData.accountInfo.entityId,
                        Type = PlayfabUtils.ENTITY_TYPE
                    },
                    Attributes = new MatchmakingPlayerAttributes
                    {
                        DataObject = new LatenciesData
                        {
                            Latencies = new List <Latency>
                            {
                                { new Latency {
                                      region = qosRegion, latency = pingTime
                                  } }
                            }
                        }
                    }
                },
                GiveUpAfterSeconds = PlayfabUtils.MATCHMAKING_TIMEOUT,
                QueueName          = PlayfabUtils.MATCHMAKING_NAME
            };

            PlayFabMultiplayerAPI.CreateMatchmakingTicket(request, OnTicketCreated, OnError);
        }, OnError);
    }
Exemplo n.º 9
0
    public void CreateBuildWithCustomContainer(BuildBundleID identity)
    {
        ShowLoader();
        try {
            PortID[]   configuredPorts   = portButton.transform.parent.GetComponentsInChildren <PortID>(false);
            RegionID[] configuredRegions = regionButton.transform.parent.GetComponentsInChildren <RegionID>(false);

            if (configuredPorts.Length == 0)
            {
                Inform("Error: Ports cannot be empty! Please add a port.");
                return;
            }

            if (configuredRegions.Length == 0)
            {
                Inform("Error: Regions cannot be empty! Please add a region.");
                return;
            }

            List <Port> portList = new List <Port>();
            List <BuildRegionParams> regionList = new List <BuildRegionParams>();

            foreach (var port in configuredPorts)
            {
                portList.Add(port.portIDParams);
            }

            foreach (var region in configuredRegions)
            {
                regionList.Add(region.regionIDParams);
            }

            PlayFabMultiplayerAPI.CreateBuildWithCustomContainer(new CreateBuildWithCustomContainerRequest {
                BuildName               = identity.buildName.text,
                ContainerFlavor         = GetEnumValue <ContainerFlavor>(identity.containerFlavor.options[identity.containerFlavor.value].text),
                ContainerImageReference = new ContainerImageReference {
                    ImageName = identity.containerName.text,
                    Tag       = identity.containerTag.text
                },
                ContainerRunCommand         = "echo \"Server is being allocated...\" >> /data/GameLogs/Server.log",
                MultiplayerServerCountPerVm = int.Parse(identity.serverCountPerVm.text),
                VmSize = GetEnumValue <AzureVmSize>(identity.vmSize.options[identity.vmSize.value].text),


                Ports = portList,
                RegionConfigurations = regionList
            },
                                                                 result => {
                Debug.Log("CREATE BUILD OK: " + result.ToJson());
                buildID.gameObject.SetActive(false);
                InformURL("Build Created Successfully!\n\nBuild ID:\n" + result.BuildId,
                          string.Format("https://developer.playfab.com/en-US/{0}/multiplayer/server/builds", PlayFabSettings.TitleId));
            },
                                                                 error => {
                Debug.LogError("CREATE BUILD FAILURE: " + error.ToString());
                Inform("Build Creation Failure!\n\n" + error.ErrorMessage);
            });
        } catch (System.Exception e) {
            Inform(e.Message);
        }
    }