The Game Servers API allows you to programmatically control the lifecycle of your dedicated server instances. The primary class for this is PlayflowServerApiClient.

PlayflowServerApiClient

This class is a C# client for the PlayFlow Game Servers REST API. It handles authentication and request signing for you.

Initialization

To use the client, you first need to initialize it with your PlayFlow API key.

using PlayFlow.SDK.Servers;

// Your API key from the PlayFlow dashboard
string playflowApiKey = "YOUR_API_KEY_HERE"; 

private PlayflowServerApiClient _apiClient;

void Start()
{
    _apiClient = new PlayflowServerApiClient(playflowApiKey);
}

Starting a Game Server

To provision and start a new game server, you use the StartServerAsync method. You’ll need to provide a ServerCreateRequest object with the configuration for your new server.

The region, compute_size, and version_tag must match values you have configured in your PlayFlow project.

private async void StartNewServer()
{
    Debug.Log("Attempting to start a new server...");

    var serverCreateRequest = new ServerCreateRequest
    {
        name = $"MyExampleServer_{System.DateTime.UtcNow:yyyyMMddHHmmss}",
        region = "us-east", // Change to a valid region for your project
        compute_size = ComputeSizes.Small, // Or Medium, Large, etc.
        version_tag = "default", // Specify a build version tag if needed
        // ttl = 300, // Optional: Time To Live in seconds
        custom_data = new Dictionary<string, object> 
        {
            { "purpose", "helloworld_test" },
            { "started_by_script", true }
        }
    };

    try
    {
        ServerStartResponse response = await _apiClient.StartServerAsync(serverCreateRequest);
        Debug.Log($"Server Start successful! Instance ID: {response.instance_id}, Status: {response.status}");
    }
    catch (PlayFlowApiException apiEx)
    {
        Debug.LogError($"API Error starting server: {apiEx.Message}");
    }
}

The StartServerAsync method returns a ServerStartResponse object which contains the instance_id of the newly created server. You should store this ID to manage the server later.

Stopping a Game Server

To stop a running server instance, use the StopServerAsync method with the instance ID.

private async void StopServer(string instanceId)
{
    if (string.IsNullOrEmpty(instanceId))
    {
        Debug.LogWarning("No server instance ID provided.");
        return;
    }

    Debug.Log($"Attempting to stop server with Instance ID: {instanceId}...");
    try
    {
        ServerStopResponse response = await _apiClient.StopServerAsync(instanceId);
        Debug.Log($"Server Stop successful! Status: {response.status}");
    }
    catch (PlayFlowApiException apiEx)
    {
        Debug.LogError($"API Error stopping server {instanceId}: {apiEx.Message}");
    }
}

Listing Game Servers

You can retrieve a list of all your active servers using ListServersAsync.

private async void ListAllServers()
{
    Debug.Log("Attempting to list all servers...");
    try
    {
        // Set includeLaunching to true to also see servers that are starting up
        ServerList response = await _apiClient.ListServersAsync(includeLaunching: true);
        Debug.Log($"Total Servers: {response.total_servers}");

        foreach (var server in response.servers)
        {
            Debug.Log($"- Found Server: {server.name} (ID: {server.instance_id}), Status: {server.status}");
        }
    }
    catch (PlayFlowApiException apiEx)
    {
        Debug.LogError($"PlayFlow API Error listing servers: {apiEx.Message}");
    }
}

This is useful for creating a server browser or for administrative purposes.

Reading Server Configuration (playflow.json)

When your dedicated game server is launched by PlayFlow, a playflow.json file is placed in the root directory of your server, alongside your game executable. This file contains crucial information for your server to identify itself and understand its configuration.

playflow.json Structure

The file contains details about the server instance, including any custom data you passed when starting the server.

{
  "instance_id": "i-12345abcdef",
  "region": "us-east",
  "api-key": "your-api-key",
  "startup_args": "-logFile /logs/server.log",
  "version_tag": "v1.2.3",
  "match_id": "match-zyxwv98765",
  "arguments": "",
  "custom_data": {
    "map_name": "level1",
    "game_mode": "capture-the-flag"
  }
}

Reading the Configuration in Unity

To easily access this configuration in your Unity project, you can use the PlayFlowServerConfig class. This helper class is included in the SDK Samples and handles deserializing the JSON file for you.

To read the configuration on a game server, you can use the following code:

using PlayFlow;
using UnityEngine;

public class MyGameServerManager : MonoBehaviour
{
    void Start()
    {
        var serverConfig = PlayFlowServerConfig.LoadConfig();
        if (serverConfig != null)
        {
            Debug.Log($"Successfully loaded server config for match: {serverConfig.match_id}");
            
            // You can access any custom data you passed
            if (serverConfig.custom_data.TryGetValue("map_name", out object mapName))
            {
                Debug.Log($"Map to load: {mapName}");
            }
        }
        else
        {
            Debug.LogError("Failed to load PlayFlow server config.");
        }
    }
}

Local Testing

For testing your server logic locally within the Unity Editor, you can simulate the presence of a playflow.json file.

  1. Create a Resources folder inside your Assets directory if you don’t already have one.
  2. Create a new JSON file named playflow.json inside Assets/Resources.
  3. Populate it with your desired test configuration. You can use the structure example from above.
  4. Use the LoadConfig method with useLocalConfig set to true to load your local file.
// Inside a method running in the Unity Editor
var localConfig = PlayFlowServerConfig.LoadConfig(useLocalConfig: true);
if (localConfig != null)
{
    Debug.Log($"Loaded local config for match: {localConfig.match_id}");
}

This approach allows you to develop and test your server’s startup and configuration logic without needing to deploy it to PlayFlow for every change.