为什么WebSocket ReceiveAsync花费500毫秒

时间:2018-07-31 11:52:35

标签: asp.net performance asp.net-core websocket

我有一个简单的asp.net核心套接字服务器,这是中间件的Invoke()方法:

 public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await  _next.Invoke(context);
                return;
            }
            CancellationToken cancellationToken = context.RequestAborted;
            var socket = await context.WebSockets.AcceptWebSocketAsync();

            //await _manager.Listen(canctllationToken, socket);
            //while (!cancellationToken.IsCancellationRequested)

            for (int i = 0; i < 25; i++)
            {
                var arr = new ArraySegment<byte>(new byte[1024]);

                var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                var res = await socket.ReceiveAsync(arr, cancellationToken);

                watch.Stop();
                _logger.LogInformation("RECEIVING TIME: " + watch.ElapsedMilliseconds.ToString());

                var resMess = Encoding.UTF8.GetString(arr.Array, 0, res.Count);

                var response = Encoding.UTF8.GetBytes($"response from server{resMess}");
                var resArr = new ArraySegment<byte>(response);

                var watch2 = System.Diagnostics.Stopwatch.StartNew();
                await socket.SendAsync(resArr, System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);

                watch2.Stop();
                _logger.LogInformation("SENDING TIME: " + watch2.ElapsedMilliseconds.ToString());
            }

        }

然后,我有一个简单的控制台客户端,代码:

 private ClientWebSocket _socket;
 public SocketManager(string uri)
        {
            _socket = new ClientWebSocket();
        }
        public async Task Connect(string uri)
        {
            await _socket.ConnectAsync(new Uri(uri), CancellationToken.None);
            Console.WriteLine("connected");
        }
        public async Task Run()
        {
            await Connect(_uri);
            try
            {


                // the code that you want to measure comes here


                for (int i = 0; i < 25; i++)
                {
                    Console.WriteLine("Enter message:");
                    var stringMessage = "mess";

                    var response = Encoding.UTF8.GetBytes(stringMessage);
                    var resArr = new ArraySegment<byte>(response);

                    var watch = System.Diagnostics.Stopwatch.StartNew();

                    await _socket.SendAsync(resArr, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);

                    watch.Stop();
                    Console.WriteLine("SENDING TIME:" + watch.ElapsedMilliseconds);

                    var arr = new ArraySegment<byte>(new byte[1024]);

                    var watch2 = System.Diagnostics.Stopwatch.StartNew();

                    var res = await _socket.ReceiveAsync(arr, CancellationToken.None);

                    watch2.Stop();
                    Console.WriteLine("RECEIVING TIME: " + watch2.ElapsedMilliseconds);

                    var resMess = Encoding.UTF8.GetString(arr.Array, 0, res.Count);

                    Console.WriteLine(resMess);
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                await _socket.CloseAsync(WebSocketCloseStatus.InternalServerError, "error", CancellationToken.None);
            }
        }

screenshot of the output

我真的不明白,为什么双方都需要500毫秒来接收时间,如果我只在客户端中保留接收方法,而在服务器中发送方法,那将花费我0-5毫秒。代码服务器:

for (int i = 0; i < 25; i++)
            {
                //var arr = new ArraySegment<byte>(new byte[1024]);

                //var watch = System.Diagnostics.Stopwatch.StartNew();
                //// the code that you want to measure comes here

                //var res = await socket.ReceiveAsync(arr, cancellationToken);

                //watch.Stop();
                //_logger.LogInformation("RECEIVING TIME: " + watch.ElapsedMilliseconds.ToString());

                //var resMess = Encoding.UTF8.GetString(arr.Array, 0, res.Count);

                var response = Encoding.UTF8.GetBytes($"response from server....");
                var resArr = new ArraySegment<byte>(response);

                var watch2 = System.Diagnostics.Stopwatch.StartNew();
                await socket.SendAsync(resArr, System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);

                watch2.Stop();
                _logger.LogInformation("SENDING TIME: " + watch2.ElapsedMilliseconds.ToString());
            }

客户代码:

for (int i = 0; i < 25; i++)
                {
                    //Console.WriteLine("Enter message:");
                    //var stringMessage = "mess";

                    //var response = Encoding.UTF8.GetBytes(stringMessage);
                    //var resArr = new ArraySegment<byte>(response);

                    //var watch = System.Diagnostics.Stopwatch.StartNew();

                    //await _socket.SendAsync(resArr, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);

                    //watch.Stop();
                    //Console.WriteLine("SENDING TIME:" + watch.ElapsedMilliseconds);

                    var arr = new ArraySegment<byte>(new byte[1024]);

                    var watch2 = System.Diagnostics.Stopwatch.StartNew();

                    var res = await _socket.ReceiveAsync(arr, CancellationToken.None);

                    watch2.Stop();
                    Console.WriteLine("RECEIVING TIME: " + watch2.ElapsedMilliseconds);

                    var resMess = Encoding.UTF8.GetString(arr.Array, 0, res.Count);

                    Console.WriteLine(resMess);
                }
                Console.ReadLine();

输出为: screenshot 0 milliseconds working

抱歉,缺少代码样式,它是快速示例,但是请有人向我解释一下,为什么?

0 个答案:

没有答案