node.js http.agent keepalive如何工作?

时间:2018-07-24 12:57:40

标签: node.js http keep-alive

我同时运行了许多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')
})

0 个答案:

没有答案