HTTP keep-alive in node.js

后端 未结 3 533
南旧
南旧 2020-12-06 06:19

I am trying to set-up a HTTP client to keep the underlying connection open (keep-alive) in node.js, but it seems that the behaviour does not correspond to the docs (http://n

相关标签:
3条回答
  • 2020-12-06 07:09

    If I'm not mistaken the connection pool was implemented in 0.12.

    So if you want to have a connection pool prior 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 you want to use the HTTP core module directly, then you can use this to initialize your agent:

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

    Notice the keepAlive: true property, that is required to keep the socket open.

    You can pass an agent to the request module as well, again that works only on 0.12+ otherwise it defaults to internal pool implementation.

    0 讨论(0)
  • 2020-12-06 07:13

    The below worked for me in 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 the method calls returns data in one socket connection. You pass the options in each method call

    0 讨论(0)
  • 2020-12-06 07:16

    I guess it should work on node 0.12+. You may also want to use a different agent for this purpose. For example keep-alive-agent can do what you want:

    var KeepAliveAgent = require('keep-alive-agent'),
        agent = new KeepAliveAgent();
    
    0 讨论(0)
提交回复
热议问题