} // End Constructor

        public async System.Threading.Tasks.Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);

                return;
            }

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

            string socketId = System.Guid.NewGuid().ToString();

            _sockets.TryAdd(socketId, currentSocket);

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

                string response = await ReceiveStringAsync(currentSocket, ct);

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

                    continue;
                }

                foreach (System.Collections.Generic.KeyValuePair <string, WebSocket> socket in _sockets)
                {
                    if (socket.Value.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        continue;
                    }

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

            WebSocket dummy;

            _sockets.TryRemove(socketId, out dummy);

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

            currentSocket.Dispose();
        } // End Sub Invoke
Пример #2
0
        public async System.Threading.Tasks.Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            context.Response.OnStarting(delegate(object state)
            {
                sw.Stop();

                string elapsed = sw.Elapsed.ToString("h':'mm':'ss'.'fffffff"
                                                     , System.Globalization.CultureInfo.InvariantCulture
                                                     );

                // context.Response.Headers.Add("X-Elapsed-Time", sw.ElapsedTicks.ToString());
                // context.Response.Headers.Add("X-Elapsed-Time", elapsed);
                context.Response.Headers["X-Elapsed-Time"] = elapsed;

                return(System.Threading.Tasks.Task.FromResult(0));
            }, null);

            await _next.Invoke(context);
        } // End Function Invoke