使用http.request时抛出connect ECONNREFUSED
使用http.request 发请求时遇到奇怪的问题:创建一个server,一秒后(确保server启动完成)向该server发1000个请求,按理说1000个请求也就才占用我电脑上1000个端口,不应该是什么大问题。但执行到900个请求左右之后,http.request还是报了ECONNREFUSED
错误
const http = require('http');
// create server
http.createServer(function(req, res){
res.end('ok')
}).listen(9900)
// issue 1000 requests after 1 second
setTimeout( async function(){
for(let i=0;i<1000;i++) { // werid: it works well after changing 1000 to 800
request();
}
}, 1000 )
// actually I don't care if the Promise is resolved or rejected,
// so I don't await or chain then.
function request() {
return new Promise((resolve, reject) => {
const option = {
protocol: 'http:',
host: 'localhost',
port: 9900,
path: '/',
agent: false,
method: 'GET'
};
const req = http.request(option, function(res) {
res.setEncoding('utf8');
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
console.log(body)
resolve(body)
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
console.log(e.stack)
process.exit(1)
});
req.end();
})
}
错误如下。但是我把for循环的次数改为800就没问题,所有请求都能执行成功。1000就不行。。。 凌乱了,多谢指教
problem with request: connect ECONNREFUSED 127.0.0.1:9900
Error: connect ECONNREFUSED 127.0.0.1:9900
at Object._errnoException (util.js:1024:11)
at _exceptionWithHostPort (util.js:1046:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)