gpt4 book ai didi

node.js - node.js 中的 HTTP 保持事件状态

转载 作者:IT老高 更新时间:2023-10-28 23:26:23 24 4
gpt4 key购买 nike

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

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

似乎每次请求都会关闭套接字并创建一个新的套接字。我已经在 Ubuntu 14.04 下使用 node.js 0.10.25 和 0.10.36 对此进行了测试。

有没有人能够保持活力去工作?

代码如下:

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 之前有一个连接池,你可以简单地使用 request模块:

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

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

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

注意 keepAlive: true 属性,该属性需要保持套接字打开。

您可以将代理传递给 request模块,同样只适用于 0.12+,否则默认为内部池实现。

关于node.js - node.js 中的 HTTP 保持事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com