private void AtualizarLista(UserSocket user, CancellationToken ct, TipoMensagem tipo) { string[] listaNomes = _sockets.Where(x => x.Value.State == WebSocketState.Open) .Select(x => x.Key.Nome) .ToArray(); SendAllSockets(Newtonsoft.Json.JsonConvert.SerializeObject(new { Tipo = tipo.ToString(), Lista = listaNomes, User = user }), ct); }
public async Task Invoke(HttpContext context) { if (context.Request.Path == "/wsChat") { if (!context.WebSockets.IsWebSocketRequest) { await _next.Invoke(context); return; } CancellationToken ct = context.RequestAborted; WebSocket currentSocket = await context.WebSockets.AcceptWebSocketAsync(); Guid socketId = Guid.NewGuid(); UserSocket user = new UserSocket { Id = socketId, Nome = context.Request.Query["username"] }; _sockets.TryAdd(user, currentSocket); AtualizarLista(user, ct, TipoMensagem.ListaUsuarios); while (true) { if (ct.IsCancellationRequested) { break; } var response = await ReceiveStringAsync(currentSocket, ct); if (string.IsNullOrEmpty(response)) { if (currentSocket.State != WebSocketState.Open) { if (_sockets.Keys.Any(x => x.Id == socketId)) { WebSocket dummy; _sockets.TryRemove(user, out dummy); AtualizarLista(user, ct, TipoMensagem.Sair); } break; } continue; } SendAllSockets(Newtonsoft.Json.JsonConvert.SerializeObject(new { Tipo = TipoMensagem.Mensagem.ToString(), user.Id, user.Nome, Mensagem = response }), ct); } await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct); currentSocket.Dispose(); } else { await _next.Invoke(context); return; } }