为什么setTimeout阻止我的Node.js应用程序?

拿这个代码,一个Http服务器的典型节点js例子,我添加了一个5秒的延迟来模拟一些在别处发生的asynchronous工作:

const http = require('http'); const hostname = '127.0.0.1'; const port = 8080; http.createServer((req, res) => { setTimeout(()=>{ res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); },5000); }).listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); 

我期望的是,当我打开5个选项卡,比如打开每个选项卡时,延迟半秒钟,服务器应该用这个时间或多或less地“响应”每个选项卡:

 t=0s - I open first tab t=0.5s - I open second tab t=1s - I open third tab ... t=5s - First tab stops loading, server has replied t=5.5s - Second tab stops loading, server has replied t=6s - Third tab stops loading, server has replied t=6.5s - Fourth tab stops loading, server has replied t=7s - Fifth tab stops loading, server has replied 

但是,我看到的行为如下:

 t=0s - I open first tab t=0.5s - I open second tab t=1s - I open third tab ... t=5s - First tab stops loading, server has replied t=10s - Second tab stops loading, server has replied t=15s - Third tab stops loading, server has replied t=20s - Fourth tab stops loading, server has replied t=25s - Fifth tab stops loading, server has replied 

好像后来的请求在第一个请求完成之前还没有开始运行。 我在这里错过了什么? 我认为节点JS的全部要点是能够从单个线程运行asynchronous获取?

问题不在于你的代码或Node.js – 这是你如何设置你的testing。

你错误地认为你的浏览器会发出5个并发请求 ,这不会发生。 不同的浏览器具有不同的行为,但是通常浏览器将同时连接的最大数量限制到非常低的数量。 HTTP规范给出了最大的build议。 我真的很惊讶,看到Chrome只打开一个单一的连接到本地,因为我知道Chrome打开6到其他来源 – 刚刚学到了一些新的东西!

使用一个不同的工具来运行你的testing,一个你可以控制和确定它正在发出并发请求。 然后你会看到预期的行为。

作为一个例子,我运行你的代码,并用Apache Benchmark进行testing,如下所示。 参数表示: -n 10表示-n 10个请求, -c 10表示使用并发10(即并发10个请求)。 正如您在下面的结果中看到的,所有请求花费的总时间是〜5s(和“每个请求的时间”0.5s):

 ~ $ ab -n 10 -c 10 http://127.0.0.1:8080/ This is ApacheBench, Version 2.3 <$Revision: 1663405 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Server Hostname: 127.0.0.1 Server Port: 8080 Document Path: / Document Length: 12 bytes Concurrency Level: 10 Time taken for tests: 5.019 seconds Complete requests: 10 Failed requests: 0 Total transferred: 1130 bytes HTML transferred: 120 bytes Requests per second: 1.99 [#/sec] (mean) Time per request: 5019.151 [ms] (mean) Time per request: 501.915 [ms] (mean, across all concurrent requests) Transfer rate: 0.22 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.1 0 0 Processing: 5017 5018 0.3 5018 5018 Waiting: 5008 5008 0.2 5008 5009 Total: 5018 5018 0.2 5019 5019 ERROR: The median and mean for the total time are more than twice the standard deviation apart. These results are NOT reliable. Percentage of the requests served within a certain time (ms) 50% 5019 66% 5019 75% 5019 80% 5019 90% 5019 95% 5019 98% 5019 99% 5019 100% 5019 (longest request) 

似乎这只发生在一些浏览器,我试着用Safari浏览器,它按预期工作。 所以我想Chrome会同时限制同一个资源的数量