5个请求后,node.js http.get挂起到远程站点

我正在写一个简单的API端点来确定我的服务器是否能够连接到互联网。 它工作的很好,但经过5次请求(正好5次,每次)请求挂起。 当我将Google切换到Hotmail.com时,也会发生同样的事情,这让我觉得这是我的最终目的。 我需要closureshttp.get请求吗? 我以为这个函数自动closures请求的印象。

// probably a poor assumption, but if Google is unreachable its generally safe to say that the server can't access the internet // using this client side in the dashboard to enable/disable internet resources app.get('/api/internetcheck', function(req, res) { console.log("trying google..."); http.get("http://www.google.com", function(r){ console.log("Got status code!: " +r.statusCode.toString()); res.send(r.statusCode.toString()); res.end(); console.log("ended!"); }).on('error', function(e) { console.log("Got error: " + e.message); }); }); 

以下是“正好5”的原因: https : //nodejs.org/docs/v0.10.36/api/http.html#http_agent_maxsockets

在内部, http模块使用代理类来pipe理HTTP请求。 该代理将默认允许最多5个连接到同一个HTTP服务器。

在您的代码中,您不会使用Google发送的实际响应。 所以代理假设你没有完成请求,并保持连接打开。 因此,在5次请求之后,代理将不允许您再创build一个新的连接,并且将开始等待任何现有的连接完成。

显而易见的解决scheme是只消费数据:

 http.get("http://www.google.com", function(r){ r.on('data', function() { /* do nothing */ }); ... }); 

如果遇到你的/api/internetcheck路由被调用很多的问题,那么你需要允许超过5个并发连接,你可以增加连接池的大小,或者完全禁用代理(尽pipe你仍然可以需要在这两种情况下消费数据);

 // increase pool size http.globalAgent.maxSockets = 100; // disable agent http.get({ hostname : 'www.google.com', path : '/', agent : false }, ...) 

或者可能使用HEAD请求而不是GET

(PS:如果http.get生成一个错误,你仍然应该通过使用res.end()或类似的东西来结束HTTP响应)。

:在Node.js版本> = 0.11中, maxSockets设置为Infinity

如果等待时间足够长,则5个请求将超时,接下来的5个请求将进行处理,以便应用程序不会挂起,因为它最终将处理所有请求。

为了加速这个过程,你需要做一些响应数据,如r.on('data', function() {});