> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 將遊戲伺服器與 PlayFab GSDK 整合

> 以 C++、C# 或 Java 將您的遊戲伺服器與 PlayFab 遊戲伺服器 SDK (GSDK) 整合，以發出就緒信號、傳送活動訊號，並管理多人遊戲配置。

## 概觀

PlayFab 遊戲伺服器 SDK (GSDK) 提供 C++、C# 和 Java 版本。GSDK 會將您的遊戲伺服器連線至 VM 上安裝的 PlayFab 代理程式。此代理程式可協助伺服器與 PlayFab 多人遊戲平台之間的關鍵互動。

## 基本整合

若要讓您的遊戲伺服器能夠與 PlayFab 多人遊戲平台通訊，您需要與 GSDK 整合。至少，您必須在遊戲伺服器中實作 `Start` 和 `ReadyForPlayers` 方法。

```cpp theme={null}
int main()
{
    // Call this while your game is initializing; it will start sending a heartbeat to our agent and put the game server in an Initializing state
    Microsoft::Azure::Gaming::GSDK::start();

    /* Add any other initialization code your game server needs before players can connect */

    // 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 (Microsoft::Azure::Gaming::GSDK::readyForPlayers())
    {
        // readyForPlayers returns true when an allocation call has been done, a player is about to connect!
    }
    else
    {
        // readyForPlayers returns false when the server is being terminated
    }

}
```

```csharp theme={null}
static void Main(string[] args)
{
    // Call this while your game is initializing; it will start sending a heartbeat to our agent and put the game server in an Initializing state
    GameserverSDK.Start();

    /* Add any other initializion code your game server needs before players can connect */

    // 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!
    }
    else
    {
        // readyForPlayers returns false when the server is being terminated
    }

}
```

```java theme={null}
public static void main(String[] args)
{
    // Call this while your game is initializing; it will start sending a heartbeat to our agent and put the game server in an Initializing state
    GameserverSDK.start();

    /* Add any other initializion code your game server needs before players can connect */

    // 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!
    }
    else
    {
        // readyForPlayers returns false when the server is being terminated
    }

}
```

## 使用 GSDK 記錄

當您的遊戲伺服器結束時，PlayFab VM 代理程式會將所有記錄檔壓縮，並提供給您使用。  \<!--via the [GetMultiplayerServerLogs](xref:titleid.playfabapi.com.multiplayer.multiplayerserver.getmultiplayerserverlogs) API.-->

有兩種方式可以從遊戲新增記錄檔：

1. 使用 GSDK 的 `Log` 方法——它會將您自己的記錄行新增至 GSDK 記錄檔。
2. 在適當的記錄目錄中撰寫您自己的記錄檔，PlayFab VM 代理程式會將其壓縮並上傳。

```cpp theme={null}
// This will add your log line to the GSDK log file, alongside other information logged by the GSDK
Microsoft::Azure::Gaming::GSDK::logMessage("Here is a sample log");

// Alternatively, you can log your own files to the log directory
std::string logFolder = Microsoft::Azure::Gaming::GSDK::getLogsDirectory();
```

```csharp theme={null}
// This will add your log line to the GSDK log file, alongside other information logged by the GSDK
GameserverSDK.LogMessage("Here is a sample log");

// Alternatively, you can log your own files to the log directory
string logFolder = GameserverSDK.GetLogsDirectory();
```

```java theme={null}
// This will add your log line to the GSDK log file, alongside other information logged by the GSDK
GameserverSDK.log("Here is a sample log");

// Alternatively, you can log your own files to the log directory
String logFolder = GameserverSDK.getLogsDirectory();
```

## 正常關閉遊戲伺服器

在三種案例中，您的遊戲伺服器會結束：

1. 您的遊戲伺服器應用程式結束。

2. PlayFab 終止您的遊戲伺服器，因為可用的遊戲伺服器多於目前玩家負載所需的數量。

<Note>
  PlayFab *只會*終止目前非作用中的遊戲伺服器。
</Note>

3. Azure 將對裝載您遊戲伺服器的虛擬機器執行必要的維護。

對於上述 **(1)**：您可以控制何時發生，並可以在應用程式結束之前執行任何必要的清除。

對於上述 **(2)** 和 **(3)**：GSDK 提供一種方式，讓您透過指定回呼方法得知它們何時會發生。

```cpp theme={null}
// This method will be called in case #2, when PlayFab terminates the game server
void onShutdown()
{
    printf("GSDK is shutting me down!!!\n");
    /* Perform any necessary cleanup and end the program */
    std::exit(0);
}

// This method will be called in case #3, when Azure will perform maintenance on the virtual machine
void onMaintenanceScheduled(tm t)
{
#ifdef WINDOWS
    time_t local = _mkgmtime(&t);
    double delta = difftime(local, time(NULL));
    struct tm buf;
    char str[26];
    gmtime_s(&buf, &local);
    asctime_s(str, sizeof str, &buf);
    printf("UTC:   %s", str);
    localtime_s(&buf, &local);
    asctime_s(str, sizeof str, &buf);
    printf("local: %s", str);
    printf("delta: %f", delta);
#else // Linux
    time_t local = timegm(&t);
    double delta = difftime(local, time(NULL));
    printf("UTC:   %s\n", asctime(gmtime(&local)));
    printf("local: %s\n", asctime(localtime(&local)));
    printf("delta: %f\n", delta);
#endif

    /* Perform any necessary cleanup, notify your players, etc. */
}

int main()
{
        Microsoft::Azure::Gaming::GSDK::start();
        Microsoft::Azure::Gaming::GSDK::registerShutdownCallback(&onShutdown);
        Microsoft::Azure::Gaming::GSDK::registerMaintenanceCallback(&onMaintenanceScheduled);

        // Continue initializing your game
}
```

```csharp theme={null}
// This method will be called in case #2, when PlayFab terminates the game server
static void OnShutdown()
{
    GameserverSDK.LogMessage("Shutting down...");
    /* Perform any necessary cleanup and end the program */
}

// This method will be called in case #3, when Azure will perform maintenance on the virtual machine
static void OnMaintenanceScheduled(DateTimeOffset time)
{
    /* Perform any necessary cleanup, notify your players, etc. */
}

static void Main(string[] args)
{
    GameserverSDK.Start();
    GameserverSDK.RegisterShutdownCallback(OnShutdown);
    GameserverSDK.RegisterMaintenanceCallback(OnMaintenanceScheduled);

    // Continue initializing your game
}
```

```java theme={null}
// This method will be called in case #2, when PlayFab terminates the game server
private static void onShutdown()
{
    System.out.println("Shutting down...");
    /* Perform any necessary cleanup and end the program */
}

// This method will be called in case #3, when Azure will perform maintenance on the virtual machine
private static void onMaintenanceScheduled(ZonedDateTime time)
{
    /* Perform any necessary cleanup, notify your players, etc. */
}

static void Main(string[] args)
{
    GameserverSDK.start();
    GameserverSDK.registerShutdownCallback(Main::onShutdown);
    GameserverSDK.registerMaintenanceCallback(Main::onMaintenanceScheduled);

    // Continue initializing your game
}
```

## 向 PlayFab 提供有關遊戲伺服器的資訊

目前您可以使用 GSDK 向 PlayFab 傳達兩件事：

1. 您的遊戲伺服器目前的健康狀態。
2. 目前連線至您遊戲伺服器的玩家清單。

這兩項資訊會在下一次活動訊號中傳輸至 PlayFab，目前可用於報告。

```cpp theme={null}
static std::vector<Microsoft::Azure::Gaming::ConnectedPlayer> players;

void playerConnected()
{
    // When a new player connects, you can let PlayFab know by adding it to the vector of players and calling updateConnectedPlayers
    players.push_back(Microsoft::Azure::Gaming::ConnectedPlayer("player_tag"));
    Microsoft::Azure::Gaming::GSDK::updateConnectedPlayers(players);
}

// This method will be called on every heartbeat to check if your game is healthy, as such, it should return very quickly
bool isHealthy()
{
    // Return whether your game server should be considered healthy
    return true;
}

int main()
{
        Microsoft::Azure::Gaming::GSDK::start();
        Microsoft::Azure::Gaming::GSDK::registerHealthCallback(&isHealthy);

        // Continue initializing your game
}
```

```csharp theme={null}
static private List<ConnectedPlayer> players = new List<ConnectedPlayer>();

static void OnPlayerConnected()
{
    // When a new player connects, you can let PlayFab know by adding it to the vector of players and calling updateConnectedPlayers
    players.Add(new ConnectedPlayer("player_tag"));
    GameserverSDK.UpdateConnectedPlayers(players);
}

// This method will be called on every heartbeat to check if your game is healthy, as such, it should return very quickly
static bool IsHealthy()
{
    // Return whether your game server should be considered healthy
    return true;
}

static void Main(string[] args)
{
    GameserverSDK.Start();
    GameserverSDK.RegisterHealthCallback(IsHealthy);

    // Continue initializing your game
}
```

```java theme={null}
private static ArrayList<ConnectedPlayer> players = new ArrayList<ConnectedPlayer>();

private static void onPlayerConnected()
{
    // When a new player connects, you can let PlayFab know by adding it to the vector of players and calling updateConnectedPlayers
    players.add(new ConnectedPlayer("player_tag"));
    GameserverSDK.updateConnectedPlayers(players);
}

// This method will be called on every heartbeat to check if your game is healthy, as such, it should return very quickly
private static GameHostHealth getGameHealth()
{
    // Return whether your game server should be considered healthy
    return GameHostHealth.Healthy;
}

static void Main(string[] args)
{
    GameserverSDK.start();
    GameserverSDK.registerHealthCallback(Main::getGameHealth);

    // Continue initializing your game
}
```

## 在遊戲伺服器中取得組態設定

有數個與遊戲伺服器相關的 PlayFab 設定，您可以使用 GSDK 擷取。

<Note>
  其中兩個設定*實際上*是由您的用戶端在要求多人遊戲伺服器的呼叫中傳遞給 PlayFab 的。因此，在遊戲伺服器被配置之前，這些設定將*無法*供遊戲伺服器使用。
</Note>

```cpp theme={null}
// Get all the configuration values
std::unordered_map<std::string, std::string> config = Microsoft::Azure::Gaming::GSDK::getConfigSettings();

// Retrieve a particular configuration value
auto it = config.find(Microsoft::Azure::Gaming::GSDK::SESSION_COOKIE_KEY);

if (it != config.end())
{
    std::string sessionCookie = config[Microsoft::Azure::Gaming::GSDK::SESSION_COOKIE_KEY];
}

// Here some other useful configuration keys (the full list is in gsdk.h)
static constexpr const char* SERVER_ID_KEY; // ID given to your game server upon creation
static constexpr const char* LOG_FOLDER_KEY; // Path to the folder that should contain all log files
static constexpr const char* CERTIFICATE_FOLDER_KEY; // Path to the folder that contains any game certificate files
static constexpr const char* TITLE_ID_KEY; // PlayFab Title ID for this game server
static constexpr const char* BUILD_ID_KEY; // PlayFab Build ID for this game server
static constexpr const char* REGION_KEY; // Azure Region this server is running in

// These two keys are only available after allocation (once readyForPlayers returns true)
static constexpr const char* SESSION_COOKIE_KEY; // The Session Cookie you passed into the allocation call when you requested a server
static constexpr const char* SESSION_ID_KEY; // The Session ID you specified in the allocation call when you requested a server
```

```csharp theme={null}
// Get all the configuration values
IDictionary<string, string> config = GameserverSDK.getConfigSettings();

// Retrieve a particular configuration value
if (config.TryGetValue(GameserverSDK.SessionCookieKey, out string sessionCookie))
{
    // sessionCookie contains the value
}

// Here are some other useful configuration keys (the full list is in the GameserverSDK class)
public static string ServerIdKey; // ID given to your game server upon creation
public static string LogFolderKey; // Path to the folder that should contain all log files
public static string CertificateFolderKey; // Path to the folder that contains any game certificate files
public static string TitleIdKey; // PlayFab Title ID for this game server
public static string BuildIdKey; // PlayFab Build ID for this game server
public static string RegionKey; // Azure Region this server is running in

// These two keys are only available after allocation (once readyForPlayers returns true)
public static string SessionCookieKey; // The Session Cookie you passed into the allocation call when you requested a server
public static string SessionIdKey; // The Session ID you specified in the allocation call when you requested a server
```

```java theme={null}
// Get all the configuration values
Map<String, String> config = GameserverSDK.getConfigSettings();

// Retrieve a particular configuration value
if (config.containsKey(GameserverSDK.SESSION_COOKIE_KEY))
{
    String sessionCookie = config.get(GameserverSDK.SESSION_COOKIE_KEY);
}

// Here are some other useful configuration keys (the full list is in the GameserverSDK class)
public static final String SERVER_ID_KEY; // ID given to your game server upon creation
public static final String LOG_FOLDER_KEY; // Path to the folder that should contain all log files
public static final String CERTIFICATE_FOLDER_KEY; // Path to the folder that contains any game certificate files
public static final String TITLE_ID_KEY; // PlayFab Title ID for this game server
public static final String BUILD_ID_KEY; // PlayFab Build ID for this game server
public static final String REGION_KEY; // Azure Region this server is running in

// These two keys are only available after allocation (once readyForPlayers returns true)
public static final String SESSION_COOKIE_KEY; // The Session Cookie you passed into the allocation call when you requested a server
public static final String SESSION_ID_KEY; // The Session ID you specified in the allocation call when you requested a server
```


## Related topics

- [PlayFab 遊戲伺服器的基本概念](/zh-TW/services/playfab/multiplayer/servers/basics-of-a-playfab-game-server.md)
- [撰寫遊戲伺服器組建](/zh-TW/services/playfab/multiplayer/servers/author-a-game-server-build.md)
- [多人遊戲伺服器的生命週期](/zh-TW/services/playfab/multiplayer/servers/multiplayer-game-server-lifecycle.md)
- [在本機對遊戲伺服器進行偵錯以及與 PlayFab 整合](/zh-TW/services/playfab/multiplayer/servers/locally-debugging-game-servers-and-integration-with-playfab.md)
- [建立和部署 Linux 組建](/zh-TW/services/playfab/multiplayer/servers/deploying-linux-based-builds.md)
