How to send consecutive requests with HTTP keep-alive in node.js? -
i'm using node.js 0.6.18, , following code makes node.js close tcp connection between every 2 requests (verified strace on linux). how make node.js reuse same tcp connection multiple http requests (i.e. keep-alive)? please note webserver capable of keep-alive, works other clients. webserver returns chunked http response.
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 request: ' + e.message); process.exit(1); }); req.end(); } work()
i able work (verified strace) creating http.agent , setting maxsockets property 1. don't know if ideal way it; however, meet requirements. 1 thing did notice docs claimed http.agent behavior did not accurately describe how worked in practice. code below:
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 request: ' + e.message); process.exit(1); }); req.end(); } work() edit: should add did testing node.js v0.8.7
Comments
Post a Comment