我同时运行了许多http.request
代码,并遇到了ECONNREFUSED
错误。但是我自定义http.globalAgent
之后,效果很好。
我想知道两种情况下会发生什么,谢谢!
const http = require('http');
http.createServer(function(req, res) {
res.end('200');
}).listen(3301)
var getPromise = () => {
return new Promise((resolve, reject) => {
const option = {
protocol: 'http:',
host: 'localhost',
port: 3301,
path: '/',
method: 'GET'
};
const req = http.request(option, function(res) {
res.setEncoding('utf8');
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve(body)
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();
})
};
// **first I comment below two lines, it throws ECONNREFUSED**
// then I uncomment them, it works
http.globalAgent.keepAlive = true;
http.globalAgent.maxSockets = 16;
var arr = []
for (var i=0;i<10000;i++) arr.push(getPromise())
Promise.all(arr).then(function(){
console.log('done')
})