2015-01-30 13 views
7

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

Cosa mostra 'console.dir (res.headers.connection)' all'interno del proprio callback 'http.get()'? – mscdex

+0

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

risposta

0

Credo che dovrebbe funzionare sul nodo 0.12+. Potresti anche voler utilizzare un agente diverso per questo scopo. Per esempio keep-alive-agent può fare ciò che si vuole:

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

Se non sbaglio il pool di connessione è stato implementato in 0,12.

Quindi, se si vuole avere un pool di connessione prima 0,12 si può semplicemente utilizzare il modulo request:

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

Se si utilizza il nodo 0.12+ e si desidera utilizzare direttamente il modulo di base HTTP, allora si può utilizzare questo per inizializzare il vostro agente:

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

Avviso la proprietà keepAlive: true, che è necessario per mantenere il socket aperto.

È possibile inoltrare un agente al modulo request, anche in questo caso funziona solo su 0.12+ altrimenti viene impostato come valore predefinito per l'implementazione del pool interno.

+0

Ovviamente, al momento del mio post, l'ultima versione stabile di Node.js era 0.10, e i documenti che stavo collegando al documento 0.10. Grazie per la risposta, farò un tentativo quando avrò una possibilità (nel frattempo ho implementato una soluzione alternativa). – quentinadam

+0

Non ho nemmeno notato la data del post. Ad ogni modo, la mia risposta è ancora valida. – simo

0

Il sotto lavorato con me meteoriti che usa il modulo npm per 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); 

} 

Tale metodo richiede restituisce i dati in uno zoccolo di connessione. Si passano le opzioni in ciascun metodo di chiamata

Problemi correlati