I’m wondering how to get the player count of a server and display it on my website. I have searched the forums, but any links I’ve come across are down. Looking to display it like - [3/32] as an example. Don’t need the player names, just the count.
using (HttpClient client = new HttpClient())
{
var response = await client.GetStringAsync("http://ip:port/dynamic.json");
var info = JsonConvert.DeserializeObject<DynamicResponse>(response);
Console.WriteLine($"{info.Clients}/{info.MaxClients} online");
}
// 2021 edit - can use System.Text.Json, also should probably reuse HttpClient
// also in C# 9.0 or so idk you can use `using var client = new HttpClient()`
class DynamicResponse
{
[JsonProperty("hostname")]
public string Hostname { get; set; }
[JsonProperty("gametype")]
public string GameType { get; set; }
[JsonProperty("mapname")]
public string MapName { get; set; }
[JsonProperty("clients")]
public int Clients { get; set; }
[JsonProperty("iv")]
public long Version { get; set; } // not sure if this should be a long, and not just a string
[JsonProperty("sv_maxclients")]
public int MaxClients { get; set; }
}
Using Newtonsoft.Json, System.Text.Json also works but that doesn’t support automatic converting to type without writing big jsonconverter blegh (edit it does now in .NET 5)
(you can also deserialize to dynamic or JObject but MEH)
var response = await client.GetStringAsync("http://ip:port/dynamic.json");
var info = JsonConvert.DeserializeObject<DynamicResponse>(response);
Console.WriteLine($"{info.Clients}/{info.MaxClients} online");
}