This repository has been archived by the owner on Feb 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
how to send data to all connected clients or selective clients? #29
Comments
This is my solution to the problem... [WebSocketRoute("/ws")]
public class MyWebSocket : WebSocketConnection
{
private static Dictionary<Guid,MyWebSocket> connections = new Dictionary<Guid, MyWebSocket>();
public Guid UniqueId { get; }
public MyWebSocket()
{
UniqueId = Guid.NewGuid();
}
public override void OnOpen()
{
connections.Add(UniqueId, this);
System.Diagnostics.Debug.WriteLine("New websocket connected {0}, now have {1} in list", UniqueId, connections.Count);
}
public override void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
{
Close(WebSocketCloseStatus.NormalClosure, "");
connections.Remove(UniqueId);
System.Diagnostics.Debug.WriteLine("Websocket {0} closed, now have {1} in list", UniqueId, connections.Count);
}
public override void OnReceiveError(Exception error)
{
Close(WebSocketCloseStatus.ProtocolError, error.Message);
connections.Remove(UniqueId);
System.Diagnostics.Debug.WriteLine("Websocket {0} errored with {1}, now have {2} in list", UniqueId, error.Message, connections.Count);
}
public override async Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type)
{
if (type == WebSocketMessageType.Text)
{
var txt = System.Text.Encoding.UTF8.GetString(message.Array, message.Offset, message.Count);
var output = System.Text.Encoding.UTF8.GetBytes("Received: " + txt);
await SendText(output, true);
}
}
public static void Broadcast(string text, params object[] args)
{
var txtBuffer = System.Text.Encoding.UTF8.GetBytes(string.Format(text, args));
foreach(var conn in connections.Values)
{
conn.SendText(txtBuffer, true);
}
}
} so having that static method I can call |
Hello, When using this code (Framework 4.7.2) , my websocket client says that it is disconnected by the server just after open. |
@mika76 you have to put this code on a background thread and not within the MyWebSocket class
I am sending a Heartbeat message to all connected clients to see if all clients are getting the message and works great |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
No description provided.
The text was updated successfully, but these errors were encountered: