예제 #1
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                var hub       = context.RequestServices.GetService <WebSocketHub>();
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                var client = new WebSocketConnection(webSocket);
                if (!hub.Accept(client))
                {
                    // unaccepted connection
                    await client.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Too many connections!");

                    return;
                }


                //push loop
                var _ = Task.Run(async() =>
                {
                    try
                    {
                        await client.PushLoop();
                    }
                    catch (WebSocketException e)
                    {
                        Console.WriteLine(e);
                        hub.Remove(client);
                    }
                });

                await ReceiveLoop(client);

                return;
            }
            await next(context);
        }