updated datasync
This commit is contained in:
1 parent
8e16dcde0d
commit
64417a6867
2 files changed
+108
-79
No files matched your search
@@ -303,7 +303,7 @@ namespace bts.websocket_core {
|
||||
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}";
|
||||
var log_txt = $"WebSocketHandler.ProcessWebSocketRequestAsync close request";
|
||||
gtwy.HandleDisconnection(id, log_txt);
|
||||
return;
|
||||
}
|
||||
@@ -323,7 +323,7 @@ namespace bts.websocket_core {
|
||||
|
||||
} catch (WebSocketException ex) {
|
||||
var ex_str = ex.ToString();
|
||||
var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}";
|
||||
var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed Error: {ex_str}";
|
||||
gtwy.HandleDisconnection(id, log_txt);
|
||||
} catch (OperationCanceledException) {//not sure about this, read that this should just be ignored
|
||||
}
|
||||
|
||||
@@ -1,4 +1,64 @@
|
||||
namespace bts.websocket_core {
|
||||
/// <summary>
|
||||
/// class to manage thread safe client store, will change this to blocking collection
|
||||
/// </summary>
|
||||
class ClientsStore {
|
||||
private Dictionary<WebsocketClientID, ClientState> Clients { get; init; }
|
||||
private object _clientsAccessLock;
|
||||
public ClientsStore() {
|
||||
Clients = new Dictionary<WebsocketClientID, ClientState>();
|
||||
_clientsAccessLock = new object();
|
||||
}
|
||||
/// <summary>
|
||||
/// adds client to dictionary is thread safe
|
||||
/// </summary>
|
||||
/// <param name="client_id"></param>
|
||||
public void AddClient(WebsocketClientID client_id) {
|
||||
lock (_clientsAccessLock) {
|
||||
Clients.Add(client_id, new ClientState(0));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// removes client from dictionary is thread safe
|
||||
/// </summary>
|
||||
/// <param name="client_id"></param>
|
||||
public void RemoveClient(WebsocketClientID client_id) {
|
||||
lock (_clientsAccessLock) {
|
||||
if (Clients.ContainsKey(client_id))
|
||||
Clients.Remove(client_id);
|
||||
}
|
||||
}
|
||||
public IEnumerator<KeyValuePair<WebsocketClientID, ClientState>> GetEnumerator() {
|
||||
lock (_clientsAccessLock) {
|
||||
return Clients.GetEnumerator();
|
||||
}
|
||||
}
|
||||
public ClientState this[WebsocketClientID clientId] {
|
||||
get {
|
||||
lock (_clientsAccessLock) {
|
||||
if (Clients.TryGetValue(clientId, out var clientState)) {
|
||||
return clientState;
|
||||
} else {
|
||||
throw new ArgumentException($"{nameof(clientId)} not found in the Clients dictionary");
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
lock (_clientsAccessLock) {
|
||||
if (Clients.ContainsKey(clientId)) {
|
||||
Clients[clientId] = value;
|
||||
} else {
|
||||
throw new ArgumentException($"{nameof(clientId)} not found in the Clients dictionary");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public int Count() {
|
||||
lock (_clientsAccessLock) {
|
||||
return Clients.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Immutable to store the state of the client
|
||||
/// </summary>
|
||||
@@ -16,89 +76,55 @@ namespace bts.websocket_core {
|
||||
/// it over to the business layer CURRENT VERSION IS JUST TO SHOW HOW TO USE GATEWAY
|
||||
/// </summary>
|
||||
public class WebsocketDataSync : IWebsocketDataSync {
|
||||
WebsocketConnectionGateway? Gateway;
|
||||
WebsocketConnectionGateway? gateway;
|
||||
WebsocketConnectionGateway Gateway {
|
||||
get {
|
||||
return (WebsocketConnectionGateway)Helpers.GetNonNull(gateway);
|
||||
}
|
||||
set {
|
||||
bts.Log.assert(gateway == null);
|
||||
gateway = value;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// stores the current connected clients, can be converted the concurrent dictionary
|
||||
/// </summary>
|
||||
private Dictionary<WebsocketClientID, ClientState>? clients;
|
||||
/// <summary>
|
||||
/// to access the dictionary
|
||||
/// </summary>
|
||||
private static object _clientsAccessLock = new object();
|
||||
private ClientsStore? clients = null;
|
||||
private ClientsStore Clients {
|
||||
get {
|
||||
return (ClientsStore)Helpers.GetNonNull(clients);
|
||||
}
|
||||
set {
|
||||
bts.Log.assert(clients == null);
|
||||
clients = value;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Thread that will broadcast messages to all connected messages
|
||||
/// </summary>
|
||||
private Thread? broadcast;
|
||||
private Thread Broadcast {
|
||||
get {
|
||||
return (Thread)Helpers.GetNonNull(broadcast);
|
||||
}
|
||||
set {
|
||||
bts.Log.assert(broadcast == null);
|
||||
broadcast = value;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// number of messages after which broadcast thread will disconnect that particular socket
|
||||
/// </summary>
|
||||
public uint BROADCAST_LIMIT { get; } = 20;
|
||||
/// <summary>
|
||||
/// will update getter to c# convention
|
||||
/// </summary>
|
||||
/// <returns>non nullable version</returns>
|
||||
private WebsocketConnectionGateway GetGateway() => (WebsocketConnectionGateway)GetNonNull(Gateway);
|
||||
/// <summary>
|
||||
/// will update getter to c# convention
|
||||
/// </summary>
|
||||
/// <returns>non nullable version</returns>
|
||||
private Dictionary<WebsocketClientID, ClientState> GetClients() => (Dictionary<WebsocketClientID, ClientState>)GetNonNull(clients);
|
||||
/// <summary>
|
||||
/// adds client to dictionary is thread safe
|
||||
/// </summary>
|
||||
/// <param name="client_id"></param>
|
||||
void AddClient(WebsocketClientID client_id) {
|
||||
lock (_clientsAccessLock) {
|
||||
GetClients().Add(client_id, new ClientState(0));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// removes client from dictionary is thread safe
|
||||
/// </summary>
|
||||
/// <param name="client_id"></param>
|
||||
void RemoveClient(WebsocketClientID client_id) {
|
||||
lock (_clientsAccessLock) {
|
||||
if (GetClients().ContainsKey(client_id))
|
||||
GetClients().Remove(client_id);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// will update getter to c# convention
|
||||
/// </summary>
|
||||
/// <returns>non nullable version</returns>
|
||||
private Thread GetBroadcast() => (Thread)GetNonNull(broadcast);
|
||||
/// <summary>
|
||||
/// To Avoid null reference warning, only called when object is not null, should only be called inside getNonNull, is separate function so can be changed later on
|
||||
/// </summary>
|
||||
/// <returns> non nullable version of object </returns>
|
||||
private T getObject<T>(T? obj) {
|
||||
return obj!;
|
||||
}
|
||||
/// <summary>
|
||||
/// as explained in c# documentation this can be used to instruct the compiler that obj is not null, for now this is redundant
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
private static bool IsNotNull([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) => obj != null;
|
||||
/// <summary>
|
||||
/// will assert that object is not null and return the non nullable version
|
||||
/// </summary>
|
||||
/// <returns> non nullable version of object </returns>
|
||||
private object GetNonNull(object? obj) {
|
||||
if (IsNotNull(obj)) {
|
||||
return getObject<object>(obj);
|
||||
} else {
|
||||
bts.Log.assert(false);
|
||||
return new Object();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Should be called in the start, stores pointer for gtwy and creates dictionary for clients, starts broadcast thread
|
||||
/// </summary>
|
||||
/// <param name="gtwy"></param>
|
||||
public void init(WebsocketConnectionGateway gtwy) {
|
||||
Gateway = gtwy;
|
||||
clients = new Dictionary<WebsocketClientID, ClientState>();
|
||||
clients = new ClientsStore();
|
||||
broadcast = new Thread(() => BroadcastToClients());
|
||||
broadcast.Start();
|
||||
}
|
||||
@@ -110,20 +136,23 @@ namespace bts.websocket_core {
|
||||
while (true) {
|
||||
List<WebsocketOutgoingMessage> messages = new List<WebsocketOutgoingMessage>();
|
||||
List<WebsocketClientID> toRemove = new List<WebsocketClientID>();
|
||||
lock (_clientsAccessLock) {
|
||||
foreach (var client in GetClients()) {
|
||||
messages.Add(new WebsocketOutgoingMessage(client.Key, $"New Message number: {client.Value.MessageCount}, clients connected: {GetClients().Count}"));
|
||||
GetClients()[client.Key] = client.Value.IncrementMessages(client.Value);
|
||||
if (GetClients()[client.Key].MessageCount == BROADCAST_LIMIT) {
|
||||
|
||||
foreach (var client in Clients) {
|
||||
try {
|
||||
messages.Add(new WebsocketOutgoingMessage(client.Key, $"New Message number: {client.Value.MessageCount}, clients connected: {Clients.Count()}"));
|
||||
Clients[client.Key] = client.Value.IncrementMessages(client.Value);
|
||||
if (Clients[client.Key].MessageCount == BROADCAST_LIMIT) {
|
||||
toRemove.Add(client.Key);
|
||||
}
|
||||
} catch (ArgumentException) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
//example on how to send multiple messages to multiple sockets
|
||||
GetGateway().send_to_clients(messages);
|
||||
Gateway.send_to_clients(messages);
|
||||
foreach (var key in toRemove) {
|
||||
///example on how to disconnect, this should ideally happen in its own thread
|
||||
GetGateway().HandleDisconnection(key, "closing client");
|
||||
Gateway.HandleDisconnection(key, "closing client");
|
||||
}
|
||||
Thread.Sleep(duration);
|
||||
}
|
||||
@@ -132,18 +161,18 @@ namespace bts.websocket_core {
|
||||
// Called when a new client is connected
|
||||
public void handle_connection(WebsocketClientID client_id,
|
||||
WebsocketIncomingMessage? optional_message) {
|
||||
AddClient(client_id);
|
||||
Clients.AddClient(client_id);
|
||||
var log_txt = $"WebsocketDataSync.handle_connection client_id: {client_id} " +
|
||||
$"message: {(optional_message == null ? "null" : optional_message.ToString())}";
|
||||
bts.Log.Gen.info(log_txt);
|
||||
System.Console.WriteLine(log_txt);
|
||||
if (IsNotNull(optional_message)) {
|
||||
if (optional_message != null) {
|
||||
handle_client_message(optional_message);
|
||||
}
|
||||
}
|
||||
// Called when a client is disconnected
|
||||
public void handle_disconnection(WebsocketClientID client_id) {
|
||||
RemoveClient(client_id);
|
||||
Clients.RemoveClient(client_id);
|
||||
var log_txt = $"WebsocketDataSync.handle_disconnection client_id: {client_id}";
|
||||
bts.Log.Gen.info(log_txt);
|
||||
System.Console.WriteLine(log_txt);
|
||||
@@ -154,7 +183,7 @@ namespace bts.websocket_core {
|
||||
bts.Log.Gen.info(log_txt);
|
||||
System.Console.WriteLine(log_txt);
|
||||
//example to show how to send messages to clients
|
||||
GetGateway().send_to_clients(new List<WebsocketOutgoingMessage>() { new WebsocketOutgoingMessage(message.sender_client_id, message.message_body + " RESPONSE") });
|
||||
Gateway.send_to_clients(new List<WebsocketOutgoingMessage>() { new WebsocketOutgoingMessage(message.sender_client_id, message.message_body + " RESPONSE") });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user