public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);

                return;
            }

            IUserServies        userService        = context.RequestServices.GetService(typeof(IUserServies)) as IUserServies;
            IReceiveDataHandler receiveDataHandler = context.RequestServices.GetService(typeof(IReceiveDataHandler)) as IReceiveDataHandler;

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

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

            //for new socket connection create new User
            var user = userService.CreateUser();
            var resp = JsonConvert.SerializeObject(new { user });

            await SendStringAsync(currentSocket, resp, ct);

            _sockets.TryAdd(user.Id, 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 result       = receiveDataHandler.Handle(response);
                var currentUser  = userService.Get(user.Id);
                var usersOfPaint = userService.GetUsersByPaintId(currentUser.PaintId);
                foreach (var socket in _sockets)
                {
                    if (socket.Value.State == WebSocketState.Open && socket.Key != user.Id && usersOfPaint.Any(e => e.Id == socket.Key))
                    {
                        await SendStringAsync(socket.Value, response, ct);
                    }
                }
            }

            WebSocket dummy;

            _sockets.TryRemove(user.Id, out dummy);

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

            currentSocket.Dispose();
        }
Esempio n. 2
0
        public ActionResult Get()
        {
            Guid userId = CurrentUserInfo.Id;

            return(new JsonResult(_userService.Get(userId), _serializer));
        }