diff --git a/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs b/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs index 42927d097..696b541aa 100644 --- a/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs +++ b/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs @@ -1,4 +1,3 @@ -// #nullable enable using System.Net.WebSockets; using System.Text; using System.Collections.Concurrent; @@ -7,69 +6,148 @@ using Microsoft.AspNetCore.Hosting; using System.Diagnostics.CodeAnalysis; namespace bts.websocket_core { + /// + /// Helper class that contains utility functions + /// + public class Helpers { + /// + /// Creates a logger that logs to both console and external log + /// + /// The base text to be logged + /// A logger function that takes an additional message and logs it along with the base text + public static Action GetLogger(string base_text) => ((string additional_message) => { + base_text += additional_message; + bts.Log.Gen.info(base_text); + Console.WriteLine(base_text); + }); + /// + /// Asserts that the given object is not null + /// + /// The object to be checked + /// True if the object is not null, False otherwise + public static bool AssertNotNull([NotNullWhen(true)] object? obj) { + bts.Log.assert(obj != null); + return true; + } + /// + /// Returns non nullable version of object after asseting that object was not null + /// + /// The object to be checked and returned + /// non nullable version of object + public static object GetNonNull(object? obj) => AssertNotNull(obj) ? obj : new Object(); + } public enum MessageType { Message, Close } /// - /// struct that holds client websocket and que + /// Represents a connection to a client through a WebSocket. /// public class Connection { + /// + /// The WebSocket instance associated with this connection. + /// public WebSocket Ws { get; } + /// + /// A queue that holds outgoing messages to be sent to the client. + /// public ConcurrentQueue> OutgoingQueue { get; } + /// + /// Initializes a new instance of the class. + /// + /// The WebSocket associated with this connection. public Connection(WebSocket websocket) { Ws = websocket; OutgoingQueue = new ConcurrentQueue>(); } } - class ConnectionsDictionary { - private ConcurrentDictionary connections; + class WebSocketConnectionStore { + private ConcurrentDictionary Connections { get; init; } + /// + /// Adds a new connection to the connections dictionary using the given id and connection object + /// + /// The id to use as the key for the new connection + /// The connection object to add to the dictionary public void AddConnection(WebsocketClientID id, Connection conn) { - var check = connections.TryAdd(id, conn); + var check = Connections.TryAdd(id, conn); if (!check) { var log_txt = $"WebsocketDataSync.createID client_id: {id.ToString()} Already exits"; bts.Log.Gen.warn(log_txt); - connections[id] = conn; + Connections[id] = conn; } } + /// + /// Removes a connection from the connections dictionary using the given id + /// + /// The id of the connection to remove public void RemoveConnection(WebsocketClientID id) { - if (connections.ContainsKey(id)) { - if (connections.TryRemove(id, out Connection? conn)) { + if (Connections.ContainsKey(id)) { + if (Connections.TryRemove(id, out Connection? conn)) { conn.Ws.Dispose(); } } } - public WebSocket? GetSocket(WebsocketClientID id) => connections.ContainsKey(id) ? connections[id].Ws : null; - public Connection? GetConnection(WebsocketClientID id) => connections.ContainsKey(id) ? connections[id] : null; - public ConcurrentQueue>? GetSocketQueue(WebsocketClientID id) => connections.ContainsKey(id) ? connections[id].OutgoingQueue : null; - public bool ContainsKey(WebsocketClientID id) => connections.ContainsKey(id); - public ConnectionsDictionary() { - connections = new ConcurrentDictionary(); + /// + /// Retrieves the Connection object associated with the given id + /// + /// The id of the connection to retrieve + /// The Connection object associated with the given id, or null if the id is not found + public Connection? GetConnection(WebsocketClientID id) { + if (Connections.TryGetValue(id, out var connection)) { + return connection; + } + return null; + } + /// + /// Retrieves the Connection object associated with the given id + /// + /// The id of the connection to retrieve + /// The Connection object associated with the given id, or null if the id is not found + public WebSocket? GetSocket(WebsocketClientID id) { + if (Connections.TryGetValue(id, out var connection)) { + return connection.Ws; + } + return null; + } + /// + /// Get the outgoing message queue for a specific client connection identified by the given id. + /// + /// The unique identifier for the client connection. + /// A concurrent queue of message tuples if the connection is found, null otherwise. + public ConcurrentQueue>? GetSocketQueue(WebsocketClientID id) { + if (Connections.TryGetValue(id, out var connection)) { + return connection.OutgoingQueue; + } + return null; + } + /// + /// Check if the store contains a connection with the specified id. + /// + /// The unique identifier for the client connection. + /// True if the connection is found, false otherwise. + public bool ContainsKey(WebsocketClientID id) => Connections.ContainsKey(id); + /// + /// Initializes a new instance of the class. + /// + public WebSocketConnectionStore() { + Connections = new ConcurrentDictionary(); } } - class SocketsHandler { - private Action GetLogger(string base_text) => ((string additional_message) => { - base_text += additional_message; - bts.Log.Gen.info(base_text); - Console.WriteLine(base_text); - }); - private T getObject(T? obj) => obj!; + class WebSocketHandler { - private static bool IsNotNull([NotNullWhen(true)] object? obj) => obj != null; - - private object GetNonNull(object? obj) { - if (IsNotNull(obj)) { - return getObject(obj); - } else { - bts.Log.assert(false); - return new Object(); - } - } - static bool IsSocketStateOpen(WebSocket? ws) => ws != null && ws.State != WebSocketState.Closed && ws.State != WebSocketState.Aborted && ws.State != WebSocketState.None; - public static bool IsClosedProperly(WebSocket ws) => ws.CloseStatus == WebSocketCloseStatus.NormalClosure; - private WebSocket? GetSocket(WebsocketClientID id, string error_message) { - var log = GetLogger(error_message); + 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; + /// + /// 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 + /// WebsocketConnectionGateway. + /// + /// The client ID to use to retrieve the WebSocket from the WebSocketConnectionStore. + /// The error message to log if the WebSocket is not found or not open. + /// The connected WebSocket or null if it was not found or not open. + private WebSocket? GetConnectedWebSocket(WebsocketClientID id, string error_message) { + var log = Helpers.GetLogger(error_message); var socket = Connections.GetSocket(id); if (IsSocketStateOpen(socket)) { return socket; @@ -79,13 +157,18 @@ namespace bts.websocket_core { } else { log(" failed as could not find socket in dictionary"); } - gtwy.HandleDisconnection(id, error_message);//fix this + gtwy.HandleDisconnection(id, error_message); return null; - } - - public bool NeedsDisconnect(WebsocketClientID id, Connection conn, string error_message) { - var log = GetLogger(error_message); + /// + /// Determines if a WebSocket connection needs to be disconnected + /// + /// The unique identifier of the WebSocket client + /// The Connection object of the WebSocket client + /// The error message to be logged in case of improper connection closure + /// True if the connection needs to be disconnected, False otherwise + public bool ShouldDisconnect(WebsocketClientID id, Connection conn, string error_message) { + var log = Helpers.GetLogger(error_message); var socket = conn.Ws; if (IsSocketStateOpen(socket)) { return true; @@ -96,28 +179,295 @@ namespace bts.websocket_core { } return false; } - private WebApplication? app = null; - private WebsocketServerParams? _server_params = null; - private WebsocketConnectionGateway gtwy; - private ConnectionsDictionary? connections = null; - private ConnectionsDictionary Connections { + private WebSocketConnectionStore? connections = null; + private WebSocketConnectionStore Connections { get { - return (ConnectionsDictionary)GetNonNull(connections); + return (WebSocketConnectionStore)Helpers.GetNonNull(connections); } set { bts.Log.assert(connections == null); connections = value; } } - - public SocketsHandler(WebsocketConnectionGateway gateway, ConnectionsDictionary conns) { + /// + /// Initializes a new instance of the class + /// + /// Websocket connection gateway + /// Connections dictionary + public WebSocketHandler(WebsocketConnectionGateway gateway, WebSocketConnectionStore conns) { gtwy = gateway; Connections = conns; } + /// + /// Processes a new WebSocket connection asynchronously by first handling the connection with the gateway, + /// then running two tasks concurrently: one for processing incoming requests and one for processing messages in the queue. + /// + /// The WebSocket connection to be processed + /// A task that represents the asynchronous operation + public async Task ProcessWebSocketConnectionAsync(WebSocket ws) { + var id = await gtwy.HandleConnection(new Connection(ws), null); + var pushTask = Task.Run(() => ProcessWebSocketQueueAsync(id)); + await ProcessWebSocketRequestAsync(id); + await pushTask; + } + + /// + /// Adds a message to the queue of a specific websocket client. + /// + /// The unique identifier of the client + /// The message to be added to the queue + public void AddToQueue(WebsocketClientID id, Tuple mes) { + var que = Connections.GetSocketQueue(id); + if (que == null) { + return; + } + que.Enqueue(mes); + } + /// + /// Processes the messages in the WebSocket queue for a specific client. + /// will keep running until socket is open + /// + /// The unique identifier of the client + private async Task ProcessWebSocketQueueAsync(WebsocketClientID id) { + // Get the socket for the client + var socket = GetConnectedWebSocket(id, "WebSocketHandler.ProcessWebSocketQueueAsync could not process"); + // Get the queue for the client + var que = Connections.GetSocketQueue(id); + // If either the socket or the queue is null, return + if (socket == null || que == null) { + return; + } + do { + // 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 + await Task.Delay(TimeSpan.FromMilliseconds(100)); + continue; + } + // If the message is a close request + if (message.Item1 == MessageType.Close) { + // Send a disconnect request to the client + await SendDisconnectRequestAsync(id, message.Item2); + // Notify the gateway of the client's disconnection + gtwy.NotifyDisconnection(id); + break; + } + // If the message is a regular message + else if (message.Item1 == MessageType.Message) { + // Send the message to the client + await SendWebSocketRequestAsync(id, message.Item2); + } + } while (IsSocketStateOpen(socket)); + } + /// + /// Sends a disconnect request to a websocket client, with an optional message. + /// + /// The unique identifier of the client to send the request to + /// An optional message for the logger + private async Task SendDisconnectRequestAsync(WebsocketClientID id, string message) { + var log = Helpers.GetLogger($"WebSocketHandler.SendDisconnectRequestAsync tried closing client_id: {id} with message: {message}"); + // Get the socket of the client + var sckt = Connections.GetSocket(id); + if (sckt == null) { + log(" failed as could not find socket in dictionary"); + return; + } + try { + // send a close message to the socket, using the close status 1000, which is a normal closure status + await sckt.CloseAsync((WebSocketCloseStatus)1000, "", CancellationToken.None); + log(" done succesfully"); + } catch (WebSocketException ex) { + log($" failed as client didnt respond, Exception: {ex.Message}"); + } + } + /// + /// recieves messages from a specific websocket client identified by its id. keeps running until socket remains open + /// + /// The unique identifier of the client + private async Task ProcessWebSocketRequestAsync(WebsocketClientID id) { + // Get the socket for the given client ID + var socket = GetConnectedWebSocket(id, "WebSocketHandler.ProcessWebSocketRequestAsync could not process"); + // If the socket is null, return + if (socket == null) { + return; + } + try { + // Create a buffer to receive the incoming message + ArraySegment buffer = new ArraySegment(new byte[256]); + WebSocketReceiveResult result; + string request = ""; + do { + // Receive the message + result = await socket.ReceiveAsync(buffer, CancellationToken.None); + // If the message is a close request, handle the disconnection and return + if (result.MessageType == WebSocketMessageType.Close) { + var log_txt = $"WebSocketHandler.ProcessWebSocketRequestAsync close request client_id: {id}"; + gtwy.HandleDisconnection(id, log_txt); + return; + } + if (buffer.Array != null)// added because of warning + { + // Append the received message to the request string + request += Encoding.UTF8.GetString(buffer.Array, 0, result.Count); + } else { + bts.Log.assert(false);//this should never happen + } + // If the message is the end of the message, handle the message and reset the request string + if (result.EndOfMessage) { + gtwy.HandleMessage(new WebsocketIncomingMessage(id, request)); + request = ""; + } + } while (IsSocketStateOpen(socket)); + + } catch (WebSocketException ex) { + var ex_str = ex.ToString(); + var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; + gtwy.HandleDisconnection(id, log_txt); + } catch (OperationCanceledException) {//not sure about this, read that this should just be ignored + } + } + /// + /// Sends a message to a specific websocket client identified by its id. + /// + /// The unique identifier of the client to receive the message + /// The message to be sent + public async Task SendWebSocketRequestAsync(WebsocketClientID id, string message) { + // Get the socket of the client + var socket = GetConnectedWebSocket(id, "WebSocketHandler.SendWebSocketRequestAsync could not send Request"); + if (socket == null) { + return; + } + try { + // Send the message + await socket.SendAsync(Encoding.ASCII.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None); + } catch (WebSocketException ex) { + // Handle the exception and disconnect the client + var ex_str = ex.ToString(); + var log_txt = $"WebSocketHandler.SendWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; + gtwy.HandleDisconnection(id, log_txt); + } + } + + + } + + public class WebsocketConnectionGateway : IWebsocketConnectionGateway { + + private WebApplication? app = null; + private WebsocketServerParams? _server_params = null; + private WebSocketConnectionStore? connections = null; + private WebSocketConnectionStore Connections { + get { + return (WebSocketConnectionStore)Helpers.GetNonNull(connections); + } + set { + bts.Log.assert(connections == null); + connections = value; + } + } + private IWebsocketDataSync? _sync = null; + private IWebsocketDataSync Sync { + get { + return (IWebsocketDataSync)Helpers.GetNonNull(_sync); + } + set { + bts.Log.assert(_sync == null); + _sync = value; + } + + } + private WebSocketHandler? _webSocketHandler = null; + private WebSocketHandler _WebSocketHandler { + get { + return (WebSocketHandler)Helpers.GetNonNull(_webSocketHandler); + } + set { + bts.Log.assert(_webSocketHandler == null); + _webSocketHandler = value; + } + } + + /// + /// Initializes the websocket gateway with a sync object and creates a new connections dictionary and a new WebSocketHandler. + /// + /// The object that synchronizes the data between the websocket server and other parts of the system + public void init(IWebsocketDataSync sync) { + Sync = sync; + Connections = new WebSocketConnectionStore(); + _WebSocketHandler = new WebSocketHandler(this, Connections); + } + /// + /// Creates a unique identifier for a websocket client and adds the client's connection to the list of active connections. + /// + /// The connection of the client + /// A unique identifier for the client + private WebsocketClientID createID(Connection conn) { + var id = new WebsocketClientID(); + Connections.AddConnection(id, conn); + return id; + } + /// + /// forwards an incoming message from a websocket client to sync. + /// + /// The incoming message to be handled + public void HandleMessage(WebsocketIncomingMessage message) => Sync.handle_client_message(message); + + /// + /// Notifies of a client disconnection and removes the client's connection from the list of active connections. + /// + /// The unique identifier of the disconnected client + public void NotifyDisconnection(WebsocketClientID id) { + Sync.handle_disconnection(id); + Connections.RemoveConnection(id); + } + + /// + /// Handles a new websocket connection and returns a unique identifier for the client. + /// + /// The new connection to be handled + /// An optional message associated with the connection + /// A unique identifier for the client + public async Task HandleConnection(Connection conn, WebsocketIncomingMessage? optional_message) { + var id = createID(conn); + await Task.Run(() => Sync.handle_connection(id, optional_message)); + return id; + } + + /// + /// Handles disconnection of a websocket client. + /// + /// The unique identifier of the client to be disconnected + /// An optional message to add to the logger + public void HandleDisconnection(WebsocketClientID id, string optional_message = "") { + var log = Helpers.GetLogger($"WebsocketGateway.HandleDisconnection tried closing client_id: {id} with message: {optional_message}"); + + // Get the connection of the client + var conn = Connections.GetConnection(id); + if (conn == null) { + // If the client connection is not found, log the error and notify sync about the disconnection through the Sync object + log(" could not find socket in dictionary"); + Sync.handle_disconnection(id); + return; + } + // Check if the connection needs to be disconnected + if (!_WebSocketHandler.ShouldDisconnect(id, conn, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id}")) { + // If the connection does not need to be disconnected, remove it from the Connections dictionary + Connections.RemoveConnection(id); + return; + } + // Add the disconnection message to the WebSocketHandler's message queue + _WebSocketHandler.AddToQueue(id, Tuple.Create(MessageType.Close, "")); + log(" added to que"); + } + /// + /// Starts listening for incoming websocket connections. need to call init before this + /// + /// The parameters for the websocket server includind the URL and endpoint, public void start_listening(WebsocketServerParams server_params) { // start listening, assert that init has been called already + bts.Log.assert(_sync != null); bts.Log.assert(_server_params == null); bts.Log.assert(app == null); @@ -131,239 +481,25 @@ namespace bts.websocket_core { app.Map(_server_params.Default_end_point, async context => { if (context.WebSockets.IsWebSocketRequest) { using (var ws = await context.WebSockets.AcceptWebSocketAsync()) { - await ProcessWebSocketConnectionAsync(ws); + await _WebSocketHandler.ProcessWebSocketConnectionAsync(ws); } } else { context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; } }); app.RunAsync(); - - } - public async Task ProcessWebSocketConnectionAsync(WebSocket ws) { - var id = await gtwy.HandleConnection(new Connection(ws), null); - var pushTask = Task.Run(() => ProcessWebSocketQueueAsync(id)); - await ProcessWebSocketRequestAsync(id); - await pushTask; - } - public void AddToQueue(WebsocketClientID id, Tuple mes) { - var que = Connections.GetSocketQueue(id); - if (que == null) { - return; - } - que.Enqueue(mes); - } - private async Task ProcessWebSocketQueueAsync(WebsocketClientID id) { - var socket = GetSocket(id, "SocketsHandler.ProcessWebSocketQueueAsync could not process"); - var que = Connections.GetSocketQueue(id); - if (socket == null || que == null) { - return; - } - do { - if (!que.TryDequeue(out var message)) { - await Task.Delay(TimeSpan.FromMilliseconds(100)); - continue; - } - if (message.Item1 == MessageType.Close) { - await SendDisconnectRequestAsync(id, message.Item2); - gtwy.NotifyDisconnection(id); - return; - } else if (message.Item1 == MessageType.Message) { - await SendWebSocketRequestAsync(id, message.Item2); - } - } while (IsSocketStateOpen(socket)); - } - public async Task SendDisconnectRequestAsync(WebsocketClientID id, string message) { - var log = GetLogger($"SocketsHandler.SendDisconnectRequestAsync tried closing client_id: {id} with message: {message}"); - var sckt = Connections.GetSocket(id); - if (sckt == null) { - log(" failed as could not find socket in dictionary"); - return; - } - try { - await sckt.CloseAsync((WebSocketCloseStatus)1000, "", CancellationToken.None); - log(" done succesfully"); - } catch { - log(" failed as client didnt respond"); - } - } - public async Task ProcessWebSocketRequestAsync(WebsocketClientID id) { - var socket = GetSocket(id, "SocketsHandler.ProcessWebSocketRequestAsync could not process"); - if (socket == null) { - return; - } - try { - ArraySegment buffer = new ArraySegment(new byte[256]); - WebSocketReceiveResult result; - string request = ""; - do { - result = await socket.ReceiveAsync(buffer, CancellationToken.None); - if (result.MessageType == WebSocketMessageType.Close) { - var log_txt = $"SocketsHandler.ProcessWebSocketRequestAsync close request client_id: {id}"; - gtwy.HandleDisconnection(id, log_txt); - return; - } - if (buffer.Array != null)// added because of warning - { - request += Encoding.UTF8.GetString(buffer.Array, 0, result.Count); - } else { - bts.Log.assert(false);//this should never happen - } - if (result.EndOfMessage) { - gtwy.HandleMessage(new WebsocketIncomingMessage(id, request)); - request = ""; - } - } while (IsSocketStateOpen(socket)); - - } catch (WebSocketException ex) { - var ex_str = ex.ToString(); - var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; - gtwy.HandleDisconnection(id, log_txt); - } catch (OperationCanceledException) {//not sure about this read that this should just be ignored - } - } - public async Task SendWebSocketRequestAsync(WebsocketClientID id, string message) { - var socket = GetSocket(id, "SocketsHandler.SendWebSocketRequestAsync could not send Request"); - if (socket == null) { - return; - } - try { - await socket.SendAsync(System.Text.Encoding.ASCII.GetBytes(message), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None); - } catch (WebSocketException ex) { - var ex_str = ex.ToString(); - var log_txt = $"SocketsHandler.SendWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; - gtwy.HandleDisconnection(id, log_txt); - return; - } } - - } - - /// - /// Handles all websocket related processing, interfaces with datasync, gets initial paramters from WebsocketServerParams - /// - - public class WebsocketConnectionGateway : IWebsocketConnectionGateway { - - - private WebsocketServerParams? _server_params = null; - private ConnectionsDictionary? connections = null; - private ConnectionsDictionary Connections { - get { - return (ConnectionsDictionary)GetNonNull(connections); - } - set { - bts.Log.assert(connections == null); - connections = value; - } - } - private IWebsocketDataSync? _sync = null; - private IWebsocketDataSync Sync { - get { - return (IWebsocketDataSync)GetNonNull(_sync); - } - set { - bts.Log.assert(_sync == null); - _sync = value; - } - - } - private SocketsHandler? networkHandler = null; - private SocketsHandler NetworkHandler { - get { - return (SocketsHandler)GetNonNull(networkHandler); - } - set { - bts.Log.assert(networkHandler == null); - networkHandler = value; - } - } - - - private T getObject(T? obj) { - return obj!; - } - - private static bool IsNotNull([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) => obj != null; - - - private object GetNonNull(object? obj) { - if (IsNotNull(obj)) { - return getObject(obj); - } else { - bts.Log.assert(false); - return new Object(); - } - } - - private Action GetLogger(string base_text) => ((string additional_message) => { - base_text += additional_message; - bts.Log.Gen.info(base_text); - Console.WriteLine(base_text); - }); - - /// Should be called in the start, stores pointer for sync and creates dictionary for clients, does not start server + /// + /// Sends a message to a list of websocket clients. /// - /// - public void init(IWebsocketDataSync sync) { - // first call - Sync = sync; - Connections = new ConnectionsDictionary(); - NetworkHandler = new SocketsHandler(this, Connections); - } - WebsocketClientID createID(Connection conn) { - var id = new WebsocketClientID(); - Connections.AddConnection(id, conn); - return id; - } - public void HandleMessage(WebsocketIncomingMessage message) => Sync.handle_client_message(message); - public void NotifyDisconnection(WebsocketClientID id) { - Sync.handle_disconnection(id); - Connections.RemoveConnection(id); - } - - public async Task HandleConnection(Connection conn, WebsocketIncomingMessage? optional_message) { - var id = createID(conn); - await Task.Run(() => Sync.handle_connection(id, optional_message)); - return id; - } - - - public void HandleDisconnection(WebsocketClientID id, string optional_message = "") { - var log = GetLogger($"WebsocketGateway.HandleDisconnection tried closing client_id: {id} with message: {optional_message}"); - var conn = Connections.GetConnection(id); - if (conn == null) { - log(" could not find socket in dictionary"); - Sync.handle_disconnection(id); - return; - } - if (!NetworkHandler.NeedsDisconnect(id, conn, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id}")) { - Connections.RemoveConnection(id); - return; - } - NetworkHandler.AddToQueue(id, Tuple.Create(MessageType.Close, "")); - log(" added to que"); - return; - } - - public void start_listening(WebsocketServerParams server_params) { - // start listening, assert that init has been called already - bts.Log.assert(_sync != null); - bts.Log.assert(_server_params == null); - - NetworkHandler.start_listening(server_params); - - } - + /// A collection of websocket messages to be sent to the clients public void send_to_clients( IEnumerable messages) { foreach (var om in messages) { - NetworkHandler.AddToQueue(om.receiver_client_id, Tuple.Create(MessageType.Message, om.message_body)); + // Add the message to the WebSocketHandler's message queue + _WebSocketHandler.AddToQueue(om.receiver_client_id, Tuple.Create(MessageType.Message, om.message_body)); } } - - - } } \ No newline at end of file