Trying to optimize pusher serivce

This commit is contained in:
2025-08-25 21:48:07 +08:00
parent eab2a388ae
commit 081815c512
7 changed files with 21 additions and 18 deletions

View File

@@ -32,7 +32,8 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
return;
}
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
{ KeepAliveInterval = TimeSpan.FromSeconds(60) });
var cts = new CancellationTokenSource();
var connectionKey = (accountId, deviceId);
@@ -65,7 +66,8 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
}
catch (Exception ex)
{
logger.LogError(ex, "WebSocket disconnected with user @{UserName}#{UserId} and device #{DeviceId} unexpectedly");
logger.LogError(ex,
"WebSocket disconnected with user @{UserName}#{UserId} and device #{DeviceId} unexpectedly");
}
finally
{
@@ -99,7 +101,7 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
break;
var packet = WebSocketPacket.FromBytes(buffer[..receiveResult.Count]);
_ = ws.HandlePacket(currentUser, connectionKey.DeviceId, packet, webSocket);
await ws.HandlePacket(currentUser, connectionKey.DeviceId, packet, webSocket);
}
}
catch (OperationCanceledException)
@@ -113,4 +115,4 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
}
}
}
}
}

View File

@@ -49,11 +49,18 @@ public class WebSocketService
public void Disconnect((string AccountId, string DeviceId) key, string? reason = null)
{
if (!ActiveConnections.TryGetValue(key, out var data)) return;
data.Socket.CloseAsync(
WebSocketCloseStatus.NormalClosure,
reason ?? "Server just decided to disconnect.",
CancellationToken.None
);
try
{
data.Socket.CloseAsync(
WebSocketCloseStatus.NormalClosure,
reason ?? "Server just decided to disconnect.",
CancellationToken.None
);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error while closing WebSocket for {AccountId}:{DeviceId}", key.AccountId, key.DeviceId);
}
data.Cts.Cancel();
ActiveConnections.TryRemove(key, out _);
}