Ping/Pong fix
This commit is contained in:
@@ -54,5 +54,38 @@ public sealed class MessageRouter
|
||||
var errWire = _serializer.Serialize(new ServerMessage(OpCodes.ERROR, errPayload));
|
||||
await connection.SendAsync(errWire, cancellationToken);
|
||||
}
|
||||
/// <summary>
|
||||
/// Called when a connection is closed to notify all handlers that need cleanup.
|
||||
/// This allows handlers like DungeonHandler to clean up player sessions.
|
||||
/// </summary>
|
||||
/// <param name="connectionId">The ID of the connection that was closed</param>
|
||||
public void OnDisconnect(Guid connectionId)
|
||||
{
|
||||
// Get all unique handler instances
|
||||
var uniqueHandlers = _handlersByOpcode.Values.Distinct();
|
||||
|
||||
foreach (var handler in uniqueHandlers)
|
||||
{
|
||||
// Check if handler has OnDisconnect method using reflection
|
||||
// This allows handlers to opt-in to disconnect notifications
|
||||
var onDisconnectMethod = handler.GetType().GetMethod("OnDisconnect",
|
||||
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
|
||||
|
||||
if (onDisconnectMethod != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
onDisconnectMethod.Invoke(handler, new object[] { connectionId });
|
||||
_logger.LogTrace("Called OnDisconnect on {HandlerType} for connection {ConnectionId}",
|
||||
handler.GetType().Name, connectionId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error calling OnDisconnect on {HandlerType} for connection {ConnectionId}",
|
||||
handler.GetType().Name, connectionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -156,13 +156,11 @@ public sealed class NetworkManager
|
||||
{
|
||||
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
|
||||
// Send PING message (OpCode 2)
|
||||
// WebSocketConnection.SendAsync will add the 4-byte length prefix automatically
|
||||
// So we just send the 1-byte opcode
|
||||
var pingMessage = new byte[1];
|
||||
pingMessage[0] = 2; // OpCode 2 = PING
|
||||
|
||||
await connection.SendAsync(pingMessage, cancellationToken);
|
||||
|
||||
@@ -297,15 +295,12 @@ public sealed class NetworkManager
|
||||
/// </summary>
|
||||
private Task TickAsync(CancellationToken ct)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
foreach (var (id, conn) in _connections)
|
||||
{
|
||||
if (now - conn.LastSeenUtc > _idleTimeout + TimeSpan.FromSeconds(5))
|
||||
{
|
||||
_ = CleanupAsync(conn, "idle prune");
|
||||
}
|
||||
}
|
||||
|
||||
// Example tick operations:
|
||||
// - Prune connections that haven't responded to pings
|
||||
// - Broadcast heartbeat messages
|
||||
// - Step game simulation
|
||||
// - Clean up expired sessions
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -316,42 +311,13 @@ public sealed class NetworkManager
|
||||
{
|
||||
if (_connections.TryRemove(conn.Id, out _))
|
||||
{
|
||||
if (_sessions.TryGet(conn.Id, out var accountId, out var token)
|
||||
&& accountId != 0 && !string.IsNullOrEmpty(token))
|
||||
{
|
||||
try
|
||||
{
|
||||
var onlineKey = $"online:acct:{accountId}";
|
||||
var sessKey = $"sess:{token}";
|
||||
|
||||
const string lua = @"
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
redis.call('DEL', KEYS[1])
|
||||
end
|
||||
redis.call('DEL', KEYS[2])
|
||||
return 1";
|
||||
|
||||
await _redis.Db.ScriptEvaluateAsync(lua,
|
||||
new StackExchange.Redis.RedisKey[] { onlineKey, sessKey },
|
||||
new StackExchange.Redis.RedisValue[] { token });
|
||||
|
||||
// NEW: close the SQL session audit row
|
||||
await _sessionAudit.EndAsync(accountId, token, reason);
|
||||
|
||||
_sessions.Unbind(conn.Id);
|
||||
_log.LogInformation("Logged out account {AccountId} on disconnect", accountId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogWarning(ex, "Failed logout cleanup for account {AccountId}", accountId);
|
||||
try { await _sessionAudit.EndAsync(accountId, token, reason); } catch { }
|
||||
_sessions.Unbind(conn.Id);
|
||||
}
|
||||
}
|
||||
|
||||
_log.LogInformation("Disconnected {Id} ({Reason})", conn.Id, reason);
|
||||
try { await conn.CloseAsync(reason); } catch { }
|
||||
try { await conn.DisposeAsync(); } catch { }
|
||||
_log.LogInformation("Connection cleaned up: ConnectionId={Id}, Reason={Reason}", conn.Id, reason);
|
||||
|
||||
// Notify router about disconnection for session cleanup
|
||||
_router.OnDisconnect(conn.Id);
|
||||
|
||||
// Close the connection gracefully
|
||||
await conn.CloseAsync(reason, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user