Ping/Pong

This commit is contained in:
dingo
2026-01-16 15:49:56 -05:00
parent 7f295c2802
commit 6ef48b8462
2 changed files with 301 additions and 42 deletions
+102 -12
View File
@@ -1,35 +1,125 @@
namespace Server.Networking.Messages;
namespace Server.Networking.Messages;
/// <summary>
/// Network message operation codes for client-server communication
/// </summary>
public static class OpCodes
{
/// <summary>
/// Echo test message - server echoes back the received payload
/// </summary>
public const int ECHO = 1;
/// <summary>
/// Server -> Client: Keepalive ping message to prevent idle timeout
/// Client should respond with PONG to reset idle timer
/// </summary>
public const int PING = 2;
/// <summary>
/// Client -> Server: Response to PING message
/// Indicates client is still alive and responsive
/// </summary>
public const int PONG = 3;
// ===== Authentication (100-119) =====
/// <summary>
/// Client -> Server: Register new account
/// Payload: { username: string, password: string }
/// </summary>
public const int AUTH_REGISTER = 100;
/// <summary>
/// Server -> Client: Registration result
/// Payload: { success: bool, message: string, accountId?: int }
/// </summary>
public const int AUTH_REGISTER_RESULT = 101;
/// <summary>
/// Client -> Server: Login with username and password
/// Payload: { username: string, password: string }
/// </summary>
public const int AUTH_LOGIN = 110;
/// <summary>
/// Server -> Client: Login result
/// Payload: { success: bool, message: string, token?: string }
/// </summary>
public const int AUTH_LOGIN_RESULT = 111;
/// <summary>
/// Client -> Server: Authenticate using stored token
/// Payload: { token: string }
/// </summary>
public const int AUTH_WITH_TOKEN = 112;
/// <summary>
/// Server -> Client: Token authentication result
/// Payload: { success: bool, message: string }
/// </summary>
public const int AUTH_WITH_TOKEN_RESULT = 113;
public const int ERROR = 900;
//public const int CHAR_LIST = 200;
//public const int CHAR_LIST_RESULT = 201;
// ===== Character Management (200-219) =====
/// <summary>
/// Client -> Server: Create new character
/// Payload: { name: string }
/// </summary>
public const int CHAR_CREATE = 202;
/// <summary>
/// Server -> Client: Character creation result
/// Payload: { success: bool, message: string, character?: object }
/// </summary>
public const int CHAR_CREATE_RESULT = 203;
/// <summary>
/// Client -> Server: Select character to play
/// Payload: { characterId: int }
/// </summary>
public const int CHAR_SELECT = 204;
/// <summary>
/// Server -> Client: Character selection result
/// Payload: { success: bool, message: string }
/// </summary>
public const int CHAR_SELECT_RESULT = 205;
public const int WORLD_SPAWN_REQUEST = 300; // client -> server (after select)
public const int WORLD_SPAWN = 301; // server -> client (your own + others joining)
public const int WORLD_DESPAWN = 302; // server -> client
public const int WORLD_INPUT = 310; // client -> server (per tick or at ~20 Hz)
public const int WORLD_STATE = 311; // server -> client (snapshots, ~10–20 Hz)
// ===== World/Overworld (300-319) =====
/// <summary>
/// Client -> Server: Request to spawn in world after character selection
/// </summary>
public const int WORLD_SPAWN_REQUEST = 300;
/// <summary>
/// Server -> Client: Spawn notification (your own character or other players joining)
/// </summary>
public const int WORLD_SPAWN = 301;
/// <summary>
/// Server -> Client: Despawn notification (player leaving)
/// </summary>
public const int WORLD_DESPAWN = 302;
/// <summary>
/// Client -> Server: Player input (movement, actions)
/// Sent at ~20 Hz or per tick
/// </summary>
public const int WORLD_INPUT = 310;
/// <summary>
/// Server -> Client: World state snapshot
/// Sent at ~10-20 Hz
/// </summary>
public const int WORLD_STATE = 311;
// ===== Error Messages (900-999) =====
/// <summary>
/// Server -> Client: General error message
/// Payload: { error: string }
/// </summary>
public const int ERROR = 900;
}
+199 -30
View File
@@ -1,4 +1,4 @@
using System.Collections.Concurrent;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
@@ -10,6 +10,10 @@ using StackExchange.Redis;
namespace Server.Networking;
/// <summary>
/// Manages all network connections (WebSocket and TCP), tick loop, and keepalive/ping system.
/// Now includes automatic ping mechanism to prevent idle timeout disconnections.
/// </summary>
public sealed class NetworkManager
{
private readonly ILogger<NetworkManager> _log;
@@ -21,9 +25,15 @@ public sealed class NetworkManager
private readonly TimeSpan _tickInterval;
private readonly TimeSpan _idleTimeout;
private readonly TimeSpan _pingInterval;
private readonly int _maxConnections;
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis, ISessionAudit sessionAudit)
public NetworkManager(
ILogger<NetworkManager> log,
MessageRouter router,
ISessionRegistry sessions,
IRedisManager redis,
ISessionAudit sessionAudit)
{
_log = log;
_router = router;
@@ -31,46 +41,156 @@ public sealed class NetworkManager
_redis = redis;
_sessionAudit = sessionAudit;
var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20;
// Parse tick rate from environment variable (default: 20 Hz)
var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz)
? Math.Clamp(hz, 1, 120)
: 20;
_tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz);
_idleTimeout = TimeSpan.FromSeconds(int.TryParse(Environment.GetEnvironmentVariable("IDLE_TIMEOUT_S"), out var idle) ? Math.Clamp(idle, 10, 300) : 45);
_maxConnections = int.TryParse(Environment.GetEnvironmentVariable("MAX_CONN"), out var mc) ? Math.Max(mc, 100) : 10_000;
// Parse idle timeout from environment variable (default: 90 seconds to allow for ping delays)
_idleTimeout = TimeSpan.FromSeconds(
int.TryParse(Environment.GetEnvironmentVariable("IDLE_TIMEOUT_S"), out var idle)
? Math.Clamp(idle, 10, 300)
: 90
);
// Ping interval should be less than half of idle timeout to ensure keepalive
// Default: 30 seconds (gives 3 attempts before 90 second timeout)
_pingInterval = TimeSpan.FromSeconds(
int.TryParse(Environment.GetEnvironmentVariable("PING_INTERVAL_S"), out var ping)
? Math.Clamp(ping, 5, 60)
: 30
);
_log.LogInformation("Tick={Hz}Hz IdleTimeout={Idle}s MaxConn={Max}", tickHz, _idleTimeout.TotalSeconds, _maxConnections);
// Parse max connections from environment variable (default: 10,000)
_maxConnections = int.TryParse(Environment.GetEnvironmentVariable("MAX_CONN"), out var mc)
? Math.Max(mc, 100)
: 10_000;
_log.LogInformation(
"NetworkManager initialized: Tick={Hz}Hz, IdleTimeout={Idle}s, PingInterval={Ping}s, MaxConn={Max}",
tickHz,
_idleTimeout.TotalSeconds,
_pingInterval.TotalSeconds,
_maxConnections
);
}
/// <summary>
/// Accept and handle a WebSocket connection from a client.
/// Implements ping/pong keepalive mechanism to prevent idle timeouts.
/// </summary>
public async Task AcceptWebSocketAsync(HttpContext ctx, WebSocket ws)
{
// Check if server is at capacity
if (_connections.Count >= _maxConnections)
{
await ws.CloseAsync(WebSocketCloseStatus.PolicyViolation, "server full", CancellationToken.None);
return;
}
var conn = new WebSocketConnection(ws, ctx.Connection.RemoteIpAddress == null ? null : new IPEndPoint(ctx.Connection.RemoteIpAddress, ctx.Connection.RemotePort));
// Create connection wrapper
var conn = new WebSocketConnection(
ws,
ctx.Connection.RemoteIpAddress == null
? null
: new IPEndPoint(ctx.Connection.RemoteIpAddress, ctx.Connection.RemotePort)
);
_connections[conn.Id] = conn;
_log.LogInformation("WebSocket connected: ConnectionId={Id}, RemoteEndPoint={Remote}", conn.Id, conn.RemoteEndPoint);
_log.LogInformation("WS connected {Id} {Remote}", conn.Id, conn.RemoteEndPoint);
// Start ping sender task
using var pingCancellationTokenSource = new CancellationTokenSource();
var pingTask = SendPeriodicPingsAsync(conn, pingCancellationTokenSource.Token);
try
{
// Main message receive loop
while (conn.IsAlive)
{
using var cts = new CancellationTokenSource(_idleTimeout);
var data = await conn.ReceiveAsync(cts.Token);
if (data is null) break;
using var idleTimeoutCancellationTokenSource = new CancellationTokenSource(_idleTimeout);
var data = await conn.ReceiveAsync(idleTimeoutCancellationTokenSource.Token);
if (data is null)
{
_log.LogDebug("Connection closed by client: ConnectionId={Id}", conn.Id);
break;
}
// Route message to appropriate handler
await _router.OnMessageAsync(conn, data.Value, CancellationToken.None);
}
}
catch (OperationCanceledException) { /* idle timeout */ }
catch (Exception ex) { _log.LogWarning(ex, "WS loop error {Id}", conn.Id); }
catch (OperationCanceledException)
{
_log.LogWarning("Connection idle timeout: ConnectionId={Id}", conn.Id);
}
catch (Exception ex)
{
_log.LogWarning(ex, "WebSocket loop error: ConnectionId={Id}", conn.Id);
}
finally
{
await CleanupAsync(conn, "ws closed");
// Stop ping task
pingCancellationTokenSource.Cancel();
try { await pingTask; } catch { /* ignore cancellation */ }
// Clean up connection
await CleanupAsync(conn, "websocket closed");
}
}
/// <summary>
/// Sends periodic PING messages to keep connection alive and detect disconnections.
/// Client should respond with PONG to reset idle timeout.
/// </summary>
private async Task SendPeriodicPingsAsync(IConnection connection, CancellationToken cancellationToken)
{
try
{
// Wait before sending first ping to avoid immediate ping on connection
await Task.Delay(_pingInterval, cancellationToken);
while (!cancellationToken.IsCancellationRequested && connection.IsAlive)
{
try
{
// Send PING message (OpCode 2, empty payload)
var pingMessage = new byte[5];
pingMessage[0] = 0; // Length high byte
pingMessage[1] = 0;
pingMessage[2] = 0;
pingMessage[3] = 1; // Length low byte (1 byte payload)
pingMessage[4] = 2; // OpCode 2 = PING
await connection.SendAsync(pingMessage, cancellationToken);
_log.LogTrace("Sent PING to ConnectionId={Id}", connection.Id);
}
catch (Exception ex)
{
_log.LogDebug(ex, "Failed to send PING to ConnectionId={Id}", connection.Id);
break;
}
// Wait for next ping interval
await Task.Delay(_pingInterval, cancellationToken);
}
}
catch (OperationCanceledException)
{
// Normal cancellation, connection is closing
}
catch (Exception ex)
{
_log.LogError(ex, "Unexpected error in ping sender for ConnectionId={Id}", connection.Id);
}
}
/// <summary>
/// Accept TCP connections in a loop (for legacy TCP client support if needed)
/// </summary>
public async Task AcceptTcpLoopAsync(TcpListener listener, CancellationToken stopping)
{
while (!stopping.IsCancellationRequested)
@@ -79,39 +199,79 @@ public sealed class NetworkManager
try
{
client = await listener.AcceptTcpClientAsync(stopping);
if (_connections.Count >= _maxConnections) { client.Close(); continue; }
if (_connections.Count >= _maxConnections)
{
client.Close();
continue;
}
_ = HandleTcpClientAsync(client, stopping);
}
catch (OperationCanceledException) { break; }
catch (Exception ex) { _log.LogError(ex, "TCP accept failed"); client?.Close(); }
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_log.LogError(ex, "TCP accept failed");
client?.Close();
}
}
}
/// <summary>
/// Handle an individual TCP client connection with ping/pong support
/// </summary>
private async Task HandleTcpClientAsync(TcpClient client, CancellationToken ct)
{
var conn = new TcpConnection(client);
_connections[conn.Id] = conn;
_log.LogInformation("TCP connected {Id} {Remote}", conn.Id, conn.RemoteEndPoint);
_log.LogInformation("TCP connected: ConnectionId={Id}, RemoteEndPoint={Remote}", conn.Id, conn.RemoteEndPoint);
// Start ping sender task
using var pingCancellationTokenSource = new CancellationTokenSource();
var pingTask = SendPeriodicPingsAsync(conn, pingCancellationTokenSource.Token);
try
{
while (conn.IsAlive && !ct.IsCancellationRequested)
{
using var idleCts = new CancellationTokenSource(_idleTimeout);
var linked = CancellationTokenSource.CreateLinkedTokenSource(idleCts.Token, ct);
var data = await conn.ReceiveAsync(linked.Token);
if (data is null) break;
using var idleTimeoutCancellationTokenSource = new CancellationTokenSource(_idleTimeout);
using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
idleTimeoutCancellationTokenSource.Token,
ct
);
var data = await conn.ReceiveAsync(linkedCancellationTokenSource.Token);
if (data is null)
break;
await _router.OnMessageAsync(conn, data.Value, ct);
}
}
catch (OperationCanceledException) { /* idle timeout or shutdown */ }
catch (Exception ex) { _log.LogWarning(ex, "TCP loop error {Id}", conn.Id); }
catch (OperationCanceledException)
{
_log.LogWarning("TCP connection idle timeout or shutdown: ConnectionId={Id}", conn.Id);
}
catch (Exception ex)
{
_log.LogWarning(ex, "TCP loop error: ConnectionId={Id}", conn.Id);
}
finally
{
// Stop ping task
pingCancellationTokenSource.Cancel();
try { await pingTask; } catch { /* ignore cancellation */ }
await CleanupAsync(conn, "tcp closed");
}
}
/// <summary>
/// Main server tick loop - runs game simulation, broadcasts state, etc.
/// </summary>
public async Task RunTickLoopAsync(CancellationToken stopping)
{
var timer = new PeriodicTimer(_tickInterval);
@@ -122,13 +282,21 @@ public sealed class NetworkManager
await TickAsync(stopping);
}
}
catch (OperationCanceledException) { /* shutting down */ }
finally { timer.Dispose(); }
catch (OperationCanceledException)
{
/* shutting down */
}
finally
{
timer.Dispose();
}
}
/// <summary>
/// Called every tick interval to update game state, prune idle connections, etc.
/// </summary>
private Task TickAsync(CancellationToken ct)
{
// Example: prune idle, broadcast heartbeat, step simulation, etc.
var now = DateTime.UtcNow;
foreach (var (id, conn) in _connections)
{
@@ -137,10 +305,13 @@ public sealed class NetworkManager
_ = CleanupAsync(conn, "idle prune");
}
}
// TODO: call your simulation step here
return Task.CompletedTask;
}
/// <summary>
/// Clean up a connection and remove it from tracking
/// </summary>
private async Task CleanupAsync(IConnection conn, string reason)
{
if (_connections.TryRemove(conn.Id, out _))
@@ -183,6 +354,4 @@ public sealed class NetworkManager
try { await conn.DisposeAsync(); } catch { }
}
}
}