Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Node.js http.ClientRequest.reusedSocket Property

  • Last Updated : 05 Feb, 2021

The http.ClientRequest.reusedSocket is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to check if the request is sent through a reused socket.

Syntax:

const request.reusedSocket

Parameters: This property does not accept any argument as a parameter.

Return Value: This property returns the object of the client request-host.

Example 1: Filename-index.js



Javascript




// Node.js program to demonstrate the  
// request.reusedSocket method
  
// Importing http module
const http = require('http');
  
// Create an HTTP server
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
  
// Now that server is running
server.listen(3000, '127.0.0.1', () => {
  
  // Make a request
  const options = {
    port: 3000,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };
  
  // Getting client request
  const req = http.request(options);
  
  req.host = '127.0.0.1'
  
  // Checking if the message has been
  // sent through reusedSocket or not
  // by using host method
  const v = req.reusedSocket;
  
  // Display the result
  if (v)
    console.log("message is sent through reusedSocket")
  else
    console.log("message is not sent through reusedSocket")
  
  process.exit(0)
});

Run the index.js file using the following command:

node index.js

Output:

message is not sent through reusedSocket

Example 2: Filename-index.js

Javascript




// Node.js program to demonstrate the  
// request.reusedSocket method
  
// Importing http module
const http = require('http');
  
// Create an HTTP server
http.createServer((req, res) => { })
  .listen(3000, '127.0.0.1', () => {
  
  // Getting client request
  const req = http.request({
    port: 3000,
    host: '127.0.0.1',
  });
  
  // Checking if the message has been
  // sent through reusedSocket or not
  // by using host method
  if (req.reusedSocket)
    console.log("message is sent through reusedSocket")
  else
    console.log("message is not sent through reusedSocket")
  
  process.exit(0)
});

Run the index.js file using the following command:

node index.js

Output:

message is not sent through reusedSocket

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_reusedsocket




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!