public async Task Invoke(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { return; } var socket = await context.WebSockets.AcceptWebSocketAsync(); ConnectedSocket connSocket = new ConnectedSocket(); connSocket.Socket = socket; //await _webSocketHandler.OnConnected(socket); await Receive(socket, async (result, buffer) => { if (result.MessageType == WebSocketMessageType.Text) { await _webSocketHandler.ReceiveAsync(socket, result, buffer); return; } else if (result.MessageType == WebSocketMessageType.Close) { await _webSocketHandler.OnDisconnected(connSocket); return; } }); //TODO - investigate the Kestrel exception thrown when this is the last middleware //await _next.Invoke(context); }
public void AddSocket(WebSocket socket, string Id) { ConnectedSocket connSocket = new ConnectedSocket(); connSocket.Socket = socket; _sockets.TryAdd(Id, connSocket); }
/// <summary> /// Send a message to the specified WebSocket using the WebSocket variable /// </summary> /// <param name="socket"></param> /// <param name="message"></param> /// <returns></returns> public async Task SendMessageAsync(ConnectedSocket socket, string message) { if (socket.Socket.State != WebSocketState.Open) { return; } await socket.Socket.SendAsync(buffer : new ArraySegment <byte>(array: Encoding.UTF8.GetBytes(message), offset: 0, count: Encoding.UTF8.GetBytes(message).Length), messageType : WebSocketMessageType.Text, endOfMessage : true, cancellationToken : CancellationToken.None); }
public string GetId(ConnectedSocket socket) { return(_sockets.FirstOrDefault(p => p.Value.Socket == socket.Socket).Key); }
/// <summary> /// Add the connected socket to the socket list in the communication manager in case of established connection /// </summary> /// <param name="socket"></param> /// <returns></returns> //public virtual async Task OnConnected(WebSocket socket) //{ // _communicationManager.AddSocket(socket); //} /// <summary> /// Remove the connected socket from the socket list in the communication manager in case of disconnected connection /// </summary> /// <param name="socket"></param> /// <returns></returns> public virtual async Task OnDisconnected(ConnectedSocket socket) { await _communicationManager.RemoveSocket(_communicationManager.GetId(socket)); }