pts*_*pts 10 client http keep-alive node.js
我正在使用node.js 0.6.18,以下代码使node.js关闭每两个请求之间的TCP连接(strace在Linux上验证).如何让node.js为多个HTTP请求重用相同的TCP连接(即保持活动状态)?请注意,网络服务器能够保持活力,它可以与其他客户端一起使用.Web服务器返回分块的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()
Run Code Online (Sandbox Code Playgroud)
Cha*_*per 10
我能够通过创建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()
Run Code Online (Sandbox Code Playgroud)
编辑:我应该补充一点,我使用node.js v0.8.7进行了测试
| 归档时间: |
|
| 查看次数: |
10835 次 |
| 最近记录: |