refactor: Add handy WebsocketExtensions

* IsSocketStateOpen
* IsClosedProperly
This commit is contained in:
John Colvin committed 2024-06-26 14:33:03 -04:00
1 parent fb476de0a3
commit 95aad773a2
2 files changed
+38 -15

No files matched your search

@@ -108,9 +108,6 @@ namespace bts.websocket_core {
/// can access the store but not change anything in it,
/// </summary>
class WebSocketHandler {
private static bool IsSocketStateOpen(WebSocket? ws) => ws != null && ws.State != WebSocketState.Closed && ws.State != WebSocketState.Aborted && ws.State != WebSocketState.None;
private static bool IsClosedProperly(WebSocket ws) => ws.CloseStatus == WebSocketCloseStatus.NormalClosure;
/// <summary>
/// GetConnectedWebSocket attempts to retrieve a connected WebSocket from the WebSocketConnectionStore using the provided client ID.
/// If the socket is not found or is not in an open state, it logs an error message and calls the HandleDisconnection method on the
@@ -120,16 +117,14 @@ namespace bts.websocket_core {
/// <param name="error_message">The error message to log if the WebSocket is not found or not open.</param>
/// <returns>The connected WebSocket or null if it was not found or not open.</returns>
private WebSocket? GetConnectedWebSocket(WebsocketClientID id, string error_message) {
LoggerContext logger = new(Log.Gen, error_message, "");
var socket = Connections.GetSocket(id);
if (IsSocketStateOpen(socket)) {
if (socket?.IsOpen() ?? false) {
return socket;
}
if (socket != null) {
logger.warn(" failed as Socket closed");
} else {
logger.warn(" failed as could not find socket in dictionary");
}
Log.Gen.warn(
$"GetConnectedWebsocket failed: {(socket is null ?
"could not find socket in dictionary" :
"socket is closed")}");
gtwy.HandleDisconnection(id, error_message);
return null;
}
@@ -143,10 +138,13 @@ namespace bts.websocket_core {
public bool ShouldDisconnect(WebsocketClientID id, Connection conn, string error_message) {
LoggerContext logger = new(Log.Gen, error_message, "");
var socket = conn.Ws;
if (IsSocketStateOpen(socket)) {
if (socket is null) {
return false;
}
if (socket.IsOpen()) {
return true;
}
if (!IsClosedProperly(socket)) {
if (!socket.IsClosedProperly()) {
logger.info(" closed improperly by other thread");
gtwy.NotifyDisconnection(id);
}
@@ -213,7 +211,7 @@ namespace bts.websocket_core {
if (socket == null || que == null) {
return;
}
while (IsSocketStateOpen(socket)) {
while (socket.IsOpen()) {
// Try to dequeue a message from the queue
if (!que.TryDequeue(out var message)) {
// If the queue is empty, wait for 100 milliseconds before trying again
@@ -272,7 +270,7 @@ namespace bts.websocket_core {
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[256]);
WebSocketReceiveResult result;
string request = "";
while (IsSocketStateOpen(socket)) {
while (socket.IsOpen()) {
// Receive the message
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
// If the message is a close request, handle the disconnection and return
@@ -417,7 +415,18 @@ namespace bts.websocket_core {
_server_params = server_params;
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls(_server_params.Uri());
var localServerParams = _server_params.Clone();
localServerParams.Scheme = "http";
var localUri = localServerParams.Uri();
builder.WebHost.UseUrls(localUri);
var publicServerParams = _server_params.Clone();
publicServerParams.Scheme = "https";
publicServerParams.Host = "192.168.50.94";
var publicUri = publicServerParams.Uri();
builder.WebHost.UseUrls(publicUri);
// var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddLogging(builder => {
builder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
@@ -0,0 +1,14 @@
namespace bts.websocket_core;
using System.Net.WebSockets;
public static class WebsocketExtensions {
public static bool IsOpen(this WebSocket ws) =>
ws.State switch {
WebSocketState.None or WebSocketState.Closed or WebSocketState.Aborted => false,
_ => true
};
public static bool IsClosedProperly(this WebSocket ws) =>
ws.CloseStatus == WebSocketCloseStatus.NormalClosure;
}