Exemple #1
0
        public async Task Invoke(HttpContext context, IUserChatRoomOperations chatRoomOperations)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);

                return;
            }

            CancellationToken ct            = context.RequestAborted;
            WebSocket         currentSocket = await context.WebSockets.AcceptWebSocketAsync();

            var socketId = Guid.NewGuid().ToString();

            _sockets.TryAdd(socketId, currentSocket);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                var response = await ReceiveStringAsync(currentSocket, ct);

                if (string.IsNullOrEmpty(response))
                {
                    if (currentSocket.State != WebSocketState.Open)
                    {
                        break;
                    }

                    continue;
                }
                var message = JsonConvert.DeserializeObject <MessageViewModel>(response);

                var addedMessage = chatRoomOperations.AddMessage(message);

                var responseMessage = JsonConvert.SerializeObject(addedMessage);

                foreach (var socket in _sockets)
                {
                    if (socket.Value.State != WebSocketState.Open)
                    {
                        continue;
                    }

                    await SendStringAsync(socket.Value, responseMessage, ct);
                }
            }

            WebSocket dummy;

            _sockets.TryRemove(socketId, out dummy);

            await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);

            currentSocket.Dispose();
        }
 public ChatRoomsController(IUserChatRoomOperations chatRoomOperations)
 {
     _chatRoomOperations = chatRoomOperations;
 }