1

I am using nodeJS https.Agent to make a call. I have configured the Agent such a way that it should re-use the socket.

How do I know if the same socket being re-used when I make subsequent the call to the same host? I tried req.reusedSocket but gives me false value everytime! Does that mean the socket connection is being re-created everytime?

const https = require('https');

const keepAliveAgent = new https.Agent({
    keepAlive: true,
    maxSockets: 10,
    maxTotalSockets: 100,
    timeout: 1000
})

const options = {
    hostname: 'reqres.in',
    port: 443,
    path: '/api/users',
    method: 'GET',
    agent: keepAliveAgent
};

setInterval( ()=> {
    console.log('interval execution');
    // making https request
    const req = https.request(options);

    // setting out the timeout ofter the socket connection
    req.setTimeout(1000, e => req.destroy());

    req.end();

    console.log(`is socket reused: ${req.reusedSocket}`); // giving flase value everytime

    // response handler
    req.on('response', (res)=> {

        res.on('data', (d)=> {
            process.stdout.write(d);
        });

        res.on('end', () => {
            console.log("\nfinished reading the data");
        })
    })

    // error handler: triggered when error occurs
    req.on('error', (e) => {
        if(e.code === "ECONNRESET") {
            console.log('request timed out');
        }
    })
}, 3000)

My intention is to re-use the existing connection to get the performance benefits while making large number of HTTPS calls to the same host. If I am doing it wrong then please provide the code sample to achieve the same result.

vikas kv
  • 386
  • 2
  • 15

0 Answers0