Files
systemrevivalserver/Networking/NetworkManager.cs
T
2025-11-04 14:12:47 -05:00

145 lines
5.3 KiB
C#

using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Server.Networking;
public sealed class NetworkManager
{
private readonly ILogger<NetworkManager> _log;
private readonly MessageRouter _router;
private readonly ConcurrentDictionary<Guid, IConnection> _connections = new();
private readonly TimeSpan _tickInterval;
private readonly TimeSpan _idleTimeout;
private readonly int _maxConnections;
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router)
{
_log = log;
_router = router;
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;
_log.LogInformation("Tick={Hz}Hz IdleTimeout={Idle}s MaxConn={Max}", tickHz, _idleTimeout.TotalSeconds, _maxConnections);
}
public async Task AcceptWebSocketAsync(HttpContext ctx, WebSocket ws)
{
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));
_connections[conn.Id] = conn;
_log.LogInformation("WS connected {Id} {Remote}", conn.Id, conn.RemoteEndPoint);
try
{
while (conn.IsAlive)
{
using var cts = new CancellationTokenSource(_idleTimeout);
var data = await conn.ReceiveAsync(cts.Token);
if (data is null) break;
await _router.OnMessageAsync(conn, data.Value, CancellationToken.None);
}
}
catch (OperationCanceledException) { /* idle timeout */ }
catch (Exception ex) { _log.LogWarning(ex, "WS loop error {Id}", conn.Id); }
finally
{
await CleanupAsync(conn, "ws closed");
}
}
public async Task AcceptTcpLoopAsync(TcpListener listener, CancellationToken stopping)
{
while (!stopping.IsCancellationRequested)
{
TcpClient? client = null;
try
{
client = await listener.AcceptTcpClientAsync(stopping);
if (_connections.Count >= _maxConnections) { client.Close(); continue; }
_ = HandleTcpClientAsync(client, stopping);
}
catch (OperationCanceledException) { break; }
catch (Exception ex) { _log.LogError(ex, "TCP accept failed"); client?.Close(); }
}
}
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);
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;
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); }
finally
{
await CleanupAsync(conn, "tcp closed");
}
}
public async Task RunTickLoopAsync(CancellationToken stopping)
{
var timer = new PeriodicTimer(_tickInterval);
try
{
while (!stopping.IsCancellationRequested && await timer.WaitForNextTickAsync(stopping))
{
await TickAsync(stopping);
}
}
catch (OperationCanceledException) { /* shutting down */ }
finally { timer.Dispose(); }
}
private Task TickAsync(CancellationToken ct)
{
// Example: prune idle, broadcast heartbeat, step simulation, etc.
var now = DateTime.UtcNow;
foreach (var (id, conn) in _connections)
{
if (now - conn.LastSeenUtc > _idleTimeout + TimeSpan.FromSeconds(5))
{
_ = CleanupAsync(conn, "idle prune");
}
}
// TODO: call your simulation step here
return Task.CompletedTask;
}
private async Task CleanupAsync(IConnection conn, string reason)
{
if (_connections.TryRemove(conn.Id, out _))
{
_log.LogInformation("Disconnected {Id} ({Reason})", conn.Id, reason);
await conn.CloseAsync(reason);
await conn.DisposeAsync();
}
}
}