Javascript node.js http请求在5次请求后锁定
我有一些非常简单的代码如下:Javascript node.js http请求在5次请求后锁定,javascript,node.js,http,Javascript,Node.js,Http,我有一些非常简单的代码如下: var http = require('http'); var options = { hostname: 'google.com', port: 80, path: '/' }; function makeRequest() { http.get(options, function(res) { console.log('Got response code: ', res.statusCode);
var http = require('http');
var options = {
hostname: 'google.com',
port: 80,
path: '/'
};
function makeRequest() {
http.get(options, function(res) {
console.log('Got response code: ', res.statusCode);
process.nextTick(makeRequest);
}).on('error', function(err) {
console.error('Got error: ', err);
throw err;
});
}
makeRequest();
5次请求后,它会锁定并停止工作。样本输出:
Got response code: 200
Got response code: 200
Got response code: 200
Got response code: 200
Got response code: 200
Got error: { [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
查看,它准确地解释了这里发生的事情,为什么@substack讨厌它,以及hyperquest如何避免它。默认情况下,客户端连接是池连接,有2分钟的空闲超时,默认最大池大小为5 如果不打算重用实例代理,则应在使用它之后调用destroy()方法,并避免在池中保留空闲连接。 例如:
你多久访问一次
google.com
?这与google.com无关,它发生在所有服务器上——包括我的本地主机(可以用agent:false
进行测试)@Wrikken发现得很好。@Wrikken那么我如何关闭请求,以便可以重用/关闭套接字?
var req = http.request({path: "/", host: "google.com",method: "HEAD"})
req.end();
req.on("response",function(res) {
//do something
// ....
req.destroy();
//do other things
});