Search code examples
node.jslong-polling

Node.js long polling request


I'm trying to understand how to consume a remote long polling resource from my Node.js app. I tried with "request" package and the connection keeps open but I cannot read the data which comes from the remote resource.

Can someone explain me how to do that?

Thanks in advance.


Solution

  • Finally found the solution:

    const https = require('https');
    const Agent = require('agentkeepalive').HttpsAgent;
    
    const keepaliveAgent = new Agent({
      maxSockets: 100,
      maxFreeSockets: 10,
      freeSocketTimeout: 30000, // free socket keepalive for 30 seconds
    });
    
    const options = {
      host: 'server',
      port: port,
      auth: 'username:password',
      path: '/path',
      method: 'POST',
      agent: keepaliveAgent,
      headers: {
            'Accept': 'application/json'
      }
    };
    
    makeRequest();
    
    function makeRequest(){
      const req = https.request(options, res => {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
          console.log('BODY: ' + chunk);
        });
      });
      req.on('error', e => {
        console.log('problem with request: ' + e.message);
        makeRequest();
      });
      req.end();
    
      }
    
    setInterval(() => {
      if (keepaliveAgent.statusChanged) {
        if(keepaliveAgent.getCurrentStatus().resetStatus != 0){
                keepaliveAgent.setCurrentStatus();
                makeRequest();
        }
      }
    }, 2000);
    

    Packages needed:

    • https
    • agentkeepalive

    Custom modifications: Each time the server endpoint restarts, the connections close the socket and it not reconnects. To handle that I modified the node_modules/agentkeepalive/lib/agent.js and added a new value called resetStatus and a new function setCurrentStatus, so each time the connection closes, the count reset to 0 and call the makeRequest function again.

    Thanks for your time!