public static async Task RegisterWebSocket(WebSocket webSocket) { var buffer = new byte[BufferSize]; var seg = new ArraySegment <byte>(buffer); if (webSocket.State == WebSocketState.Open) { var incoming = await webSocket.ReceiveAsync(seg, CancellationToken.None); var message = MessageProcessor.ProcessMessage(Encoding.UTF8.GetString(buffer, 0, incoming.Count)); if (message.Method == Method.Connection) { var communicationHandler = new CommunicationHandler(webSocket); var id = ConnectionManager.Instance.RegisterConnection(communicationHandler, message.Source); if (id >= 0) { var response = new Message(Method.Approved, "", id.ToString(), ""); await communicationHandler.SendMessageAsync(response); await RefreshClients(); await communicationHandler.ListenForMessages(); } } } }
public void RemoveConnection(CommunicationHandler communicationHandler) { var id = connections.Single(e => e.Value.Item1 == communicationHandler).Key; Tuple <CommunicationHandler, string> value; connections.TryRemove(id, out value); }
private static async Task Acceptor(HttpContext httpContext, Func <Task> func) { if (!httpContext.WebSockets.IsWebSocketRequest) { return; } var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); await CommunicationHandler.RegisterWebSocket(webSocket); }
public int RegisterConnection(CommunicationHandler communicationHandler, string nickName) { var id = 0; while (true) { if (!connections.ContainsKey(id)) { break; } id++; } var successful = connections.TryAdd(id, new Tuple <CommunicationHandler, string>(communicationHandler, nickName)); return(successful ? id : -1); }