diff --git a/Networking/Messages/OpCodes.cs b/Networking/Messages/OpCodes.cs index 0c24e42..74261fb 100644 --- a/Networking/Messages/OpCodes.cs +++ b/Networking/Messages/OpCodes.cs @@ -1,35 +1,125 @@ -namespace Server.Networking.Messages; +namespace Server.Networking.Messages; +/// +/// Network message operation codes for client-server communication +/// public static class OpCodes { + /// + /// Echo test message - server echoes back the received payload + /// public const int ECHO = 1; + /// + /// Server -> Client: Keepalive ping message to prevent idle timeout + /// Client should respond with PONG to reset idle timer + /// + public const int PING = 2; + + /// + /// Client -> Server: Response to PING message + /// Indicates client is still alive and responsive + /// + public const int PONG = 3; + + // ===== Authentication (100-119) ===== + + /// + /// Client -> Server: Register new account + /// Payload: { username: string, password: string } + /// public const int AUTH_REGISTER = 100; + + /// + /// Server -> Client: Registration result + /// Payload: { success: bool, message: string, accountId?: int } + /// public const int AUTH_REGISTER_RESULT = 101; + /// + /// Client -> Server: Login with username and password + /// Payload: { username: string, password: string } + /// public const int AUTH_LOGIN = 110; + + /// + /// Server -> Client: Login result + /// Payload: { success: bool, message: string, token?: string } + /// public const int AUTH_LOGIN_RESULT = 111; + /// + /// Client -> Server: Authenticate using stored token + /// Payload: { token: string } + /// public const int AUTH_WITH_TOKEN = 112; + + /// + /// Server -> Client: Token authentication result + /// Payload: { success: bool, message: string } + /// 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) ===== + + /// + /// Client -> Server: Create new character + /// Payload: { name: string } + /// public const int CHAR_CREATE = 202; + + /// + /// Server -> Client: Character creation result + /// Payload: { success: bool, message: string, character?: object } + /// public const int CHAR_CREATE_RESULT = 203; + /// + /// Client -> Server: Select character to play + /// Payload: { characterId: int } + /// public const int CHAR_SELECT = 204; + + /// + /// Server -> Client: Character selection result + /// Payload: { success: bool, message: string } + /// 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) ===== + + /// + /// Client -> Server: Request to spawn in world after character selection + /// + public const int WORLD_SPAWN_REQUEST = 300; + + /// + /// Server -> Client: Spawn notification (your own character or other players joining) + /// + public const int WORLD_SPAWN = 301; + + /// + /// Server -> Client: Despawn notification (player leaving) + /// + public const int WORLD_DESPAWN = 302; + /// + /// Client -> Server: Player input (movement, actions) + /// Sent at ~20 Hz or per tick + /// + public const int WORLD_INPUT = 310; + + /// + /// Server -> Client: World state snapshot + /// Sent at ~10-20 Hz + /// + public const int WORLD_STATE = 311; + // ===== Error Messages (900-999) ===== + + /// + /// Server -> Client: General error message + /// Payload: { error: string } + /// + public const int ERROR = 900; } diff --git a/Networking/NetworkManager.cs b/Networking/NetworkManager.cs index 77df84e..831257c 100644 --- a/Networking/NetworkManager.cs +++ b/Networking/NetworkManager.cs @@ -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; +/// +/// Manages all network connections (WebSocket and TCP), tick loop, and keepalive/ping system. +/// Now includes automatic ping mechanism to prevent idle timeout disconnections. +/// public sealed class NetworkManager { private readonly ILogger _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 log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis, ISessionAudit sessionAudit) + public NetworkManager( + ILogger 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 + ); } + /// + /// Accept and handle a WebSocket connection from a client. + /// Implements ping/pong keepalive mechanism to prevent idle timeouts. + /// 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"); } } + /// + /// Sends periodic PING messages to keep connection alive and detect disconnections. + /// Client should respond with PONG to reset idle timeout. + /// + 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); + } + } + + /// + /// Accept TCP connections in a loop (for legacy TCP client support if needed) + /// 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(); + } } } + /// + /// Handle an individual TCP client connection with ping/pong support + /// 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"); } } + /// + /// Main server tick loop - runs game simulation, broadcasts state, etc. + /// 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(); + } } + /// + /// Called every tick interval to update game state, prune idle connections, etc. + /// 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; } + /// + /// Clean up a connection and remove it from tracking + /// 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 { } } } - - }