如何在node.js中使用HTTP keep-alive连续发送请求?

我正在使用node.js 0.6.18,下面的代码使node.jsclosures每两个请求之间的TCP连接(在Linux上用stracevalidation)。 如何让node.js为多个HTTP请求(即保持活动状态)重复使用相同的TCP连接? 请注意,networking服务器能够保持活跃,它可以与其他客户端一起工作。 networking服务器返回分块的HTTP响应。

 var http = require('http'); var cookie = 'FOO=bar'; function work() { var options = { host: '127.0.0.1', port: 3333, path: '/', method: 'GET', headers: {Cookie: cookie}, }; process.stderr.write('.') var req = http.request(options, function(res) { if (res.statusCode != 200) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); process.exit(1) } res.setEncoding('utf8'); res.on('data', function (chunk) {}); res.on('end', function () { work(); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); process.exit(1); }); req.end(); } work() 

我能够通过创build一个http.Agent并将其maxSockets属性设置为1来得到这个工作(validation与strace)。我不知道这是否是理想的方式来做到这一点; 但是,它确实符合要求。 我注意到的一件事是文档声称的http.Agent行为没有准确地描述它在实践中是如何工作的。 代码如下:

 var http = require('http'); var cookie = 'FOO=bar'; var agent = new http.Agent; agent.maxSockets = 1; function work() { var options = { host: '127.0.0.1', port: 3000, path: '/', method: 'GET', headers: {Cookie: cookie}, agent: agent }; process.stderr.write('.') var req = http.request(options, function(res) { if (res.statusCode != 200) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); process.exit(1) } res.setEncoding('utf8'); res.on('data', function (chunk) {}); res.on('end', function () { work(); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); process.exit(1); }); req.end(); } work() 

编辑:我应该补充说,我做了我的testingnode.js v0.8.7

你可以设置:

 http.globalAgent.keepAlive = true