///// <summary>
        ///// push message to client, must be single thead
        ///// </summary>
        ///// <param name="connection"></param>
        ///// <param name="hub"></param>
        ///// <returns></returns>
        //private async Task PushLoop(WebSocketConnection connection, WebSocketHub hub)
        //{
        //    try
        //    {
        //        await connection.PushLoop();
        //    }
        //    catch (WebSocketException e)
        //    {
        //        Console.WriteLine(e);
        //        hub.Remove(connection);
        //    }
        //}


        /// <summary>
        /// receive message from client, must be single thread
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public async Task ReceiveLoop(WebSocketConnection connection)
        {
            var result = await connection.ReceiveStringAsync();

            while (!result.CloseStatus.HasValue)
            {
                var task = Task.Run(() => Excute(connection, result.Message));
                result = await connection.ReceiveStringAsync();
            }
            await connection.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription);
        }
Exemplo n.º 2
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);
        }