Saving HTTP in node.js

I am trying to configure an HTTP client to keep the basic connection open (keep-alive) in node.js, but the behavior does not seem to match the docs ( http://nodejs.org/api/http.html#http_class_http_agent ).

I am creating a new HTTP agent by setting the maxSockets property to 1 and requesting a url (e.g. http://www.twilio.com/ ) every second.

It seems that for each request, the socket closes and a new socket is created. I tested this with node.js 0.10.25 and 0.10.36 on Ubuntu 14.04.

Could anyone be alive to work?

Here is the code:

 var http = require("http"); var agent = new http.Agent(); agent.maxSockets = 1; var sockets = []; function request(hostname, path, callback) { var options = { hostname: hostname, path: path, agent: agent, headers: {"Connection": "keep-alive"} }; var req = http.get(options, function(res) { res.setEncoding('utf8'); var body = ""; res.on('data', function (chunk) { body += chunk; }); res.on('end', function () { callback(null, res, body); }); }); req.on('error', function(e) { return callback(error); }); req.on("socket", function (socket) { if (sockets.indexOf(socket) === -1) { console.log("new socket created"); sockets.push(socket); socket.on("close", function() { console.log("socket has been closed"); }); } }); } function run() { request('www.twilio.com', '/', function (error, res, body) { setTimeout(run, 1000); }); } run(); 
+7
keep-alive
source share
3 answers

If I am not mistaken, the connection pool was implemented in 0.12.

So, if you want to have a connection pool before 0.12, you can simply use the request module:

 var request = require('request') request.get('www.twilio.com', {forever: true}, function (err, res, body) {}); 

If you are using node 0.12+ and want to use the basic HTTP module directly, you can use it to initialize your agent:

 var agent = new http.Agent({ keepAlive: true, maxSockets: 1, keepAliveMsecs: 3000 }) 

Note the keepAlive: true property, which is required to open a socket.

You can pass the agent to the request module, again, which only works with 0.12+, otherwise it will use the internal pool implementation by default.

+2
source

I think it should work on node 0.12+. You can also use another agent for this. For example, keep-alive-agent can do what you want:

 var KeepAliveAgent = require('keep-alive-agent'), agent = new KeepAliveAgent(); 
0
source

Below I worked for me in a meteor, which uses the npm module for keepaliveagent

 var agent = new KeepAliveAgent({ maxSockets: 1 }); var options = { agent:agent, headers: {"Connection":"Keep-Alive"} } try { var client = Soap.createClient(url); var result = client.myfirstfunction(args,options); //process result result = client.mysecondfunction(args,options); } 

Both calling methods return data in the same socket connection. You pass parameters in every method call

0
source

All Articles