I am trying to get a live chat service for cross-platform devices. The problem is that the System.Net.WebSockets namespace does not allow me to monitor the established connection. I can take the sessionID of the current connection, but how can I say do the following await socket.SendAsync(buffer, WebSocketMessageType.Text, CancellationToken.None) for a specific client?
If I could use Microsoft.WebSockets , I would be able to create a WebSocketCollection() and do something like client.Send(message) , but I cannot send an ArraySegment<byte[]> through it. I also think this is more for AJAX clients and websites, etc.
Now I have the following code snippet:
public class WSHandler : IHttpHandler { event NewConnectionEventHandler NewConnection; public void ProcessRequest(HttpContext context) { if (context.IsWebSocketRequest) { context.AcceptWebSocketRequest(ProcessWSChat); } } public bool IsReusable { get { return false; } } private async Task ProcessWSChat(AspNetWebSocketContext context) { WebSocket socket = context.WebSocket; int myHash = socket.GetHashCode(); while (true) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult result = await socket.ReceiveAsync( buffer, CancellationToken.None); if (socket.State == WebSocketState.Open) { string userMessage = Encoding.ASCII.GetString( buffer.Array, 0, result.Count); userMessage = "You sent: " + userMessage + " at " + DateTime.Now.ToLongTimeString() + " from ip " + context.UserHostAddress.ToString(); buffer = new ArraySegment<byte>( Encoding.ASCII.GetBytes(userMessage)); await socket.SendAsync( buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { break; } } } }
How to extend my project, save sessions / connections and call a specific user connection to send him a message?
source share