> ## 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(Game Server SDK)와 게임 서버 통합

> C++, C# 또는 Java에서 게임 서버를 PlayFab Game Server SDK(GSDK)와 통합하여 준비 상태와 하트비트를 알리고 멀티플레이어 할당을 관리합니다.

## 개요

PlayFab Game Server 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 에이전트가 모든 로그 파일을 zip으로 압축하여 사용할 수 있도록 제공합니다.  \<!--via the [GetMultiplayerServerLogs](xref:titleid.playfabapi.com.multiplayer.multiplayerserver.getmultiplayerserverlogs) API.-->

게임에서 로그 파일을 추가하는 방법에는 두 가지가 있습니다.

1. GSDK의 `Log` 메서드를 사용합니다. 이 메서드는 사용자 고유의 로그 줄을 GSDK 로그 파일에 추가합니다.
2. PlayFab VM 에이전트가 zip으로 압축하여 업로드할 적절한 로그 디렉터리에 사용자 고유의 로그 파일을 작성합니다.

```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은 현재 활성 상태가 아닌 게임 서버*만* 종료합니다.

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
}
```

## 게임 서버 내에서 구성 설정 가져오기

GSDK를 사용하여 검색할 수 있는 게임 서버 관련 PlayFab 설정이 여러 가지 있습니다.

> [!NOTE]
>
> 이러한 설정 중 두 가지는 *실제로* 멀티플레이어 서버를 요청하는 호출의 일부로 클라이언트가 PlayFab에 전달합니다. 따라서 해당 설정은 게임 서버가 할당될 때까지 게임 서버에서 사용할 수 *없습니다*.

```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과의 통합](https://devdocs.xbox.com/ko/services/playfab/multiplayer/servers/locally-debugging-game-servers-and-integration-with-playfab.md)
- [PlayFab 게임 서버 기본](https://devdocs.xbox.com/ko/services/playfab/multiplayer/servers/basics-of-a-playfab-game-server.md)
- [PlayFab Multiplayer Servers와 통합](https://devdocs.xbox.com/ko/services/playfab/multiplayer/matchmaking/multiplayer-servers.md)
- [멀티플레이어 서버의 수명 주기](https://devdocs.xbox.com/ko/services/playfab/multiplayer/servers/multiplayer-game-server-lifecycle.md)
- [게임 서버 및 로비](https://devdocs.xbox.com/ko/services/playfab/multiplayer/lobby/lobby-server-overview.md)
