HTTP保持在node.js中

我正在尝试设置一个HTTP客户端,以使底层连接在node.js中保持打开状态(保持活动状态),但似乎这种行为与文档不符( http://nodejs.org/api/http .html#http_class_http_agent )。

我正在创build一个新的HTTP代理,将maxSockets属性设置为1,并且每秒都请求一个url(例如http://www.twilio.com/ )。

似乎在每个请求的套接字被closures,并创build一个新的套接字。 我已经在Ubuntu 14.04下用node.js 0.10.25和0.10.36testing了这个。

有没有人能够继续工作?

这里是代码:

 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(); 

如果我没有错误的连接池在0.12实施。

所以如果你想在0.12之前有一个连接池,你可以简单地使用请求模块:

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

如果您使用的是节点0.12+,并且您想直接使用HTTP核心模块,那么您可以使用它来初始化您的代理:

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

注意keepAlive: true属性,保持套接字打开是必需的

您也可以将代理传递给请求模块,再次只能在0.12+以上,否则默认为内部池实现。

我想它应该在节点0.12+上工作。 您可能也想为此使用不同的代理。 例如keep-alive-agent可以做你想做的事情:

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

下面的meteor使用npm模块来保存代理

 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); } 

这两个方法调用都在一个套接字连接中返回数据。 您在每个方法调用中传递选项