Sto provando a configurare un client HTTP per mantenere la connessione sottostante aperta (keep-alive) in node.js, ma sembra che il comportamento non corrisponda ai documenti (http://nodejs.org/api/http.html#http_class_http_agent).HTTP keep-alive in node.js
Sto creando un nuovo agente HTTP, impostando la proprietà maxSockets su 1 e richiedendo un url (ad esempio http://www.twilio.com/
) ogni secondo.
Sembra che su ogni richiesta il socket viene chiuso e viene creato un nuovo socket. Ho provato questo con node.js 0.10.25 e 0.10.36 con Ubuntu 14.04.
Qualcuno è riuscito a tenere in vita al lavoro?
Ecco il codice:
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();
Cosa mostra 'console.dir (res.headers.connection)' all'interno del proprio callback 'http.get()'? – mscdex
L'ho già verificato e l'host restituisce l'intestazione "Connessione: keep-alive" nella risposta, a indicare che accetta di mantenere aperta la connessione. – quentinadam