我使用的是TCP 0.6.18,下面的代码让node.js每隔两个请求就关闭一次node.js连接(用Linux上的strace
验证)。如何让node.js对多个HTTP请求重用同一个TCP连接(即保持活动状态)?请注意,with服务器能够保持活动状态,它可以与其他客户端一起工作。The服务器返回一个分块的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()
发布于 2012-09-03 15:39:42
我能够通过创建一个http.Agent
并将其maxSockets
属性设置为1来使其工作(使用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()
编辑:我应该补充说,我是使用node.js v0.8.7进行测试的
发布于 2016-01-14 08:26:40
您只需设置:
http.globalAgent.keepAlive = true
https://stackoverflow.com/questions/10895901
复制