Skip to content
Related Articles

Related Articles

Improve Article
Node.js http.ClientRequest.socket Property
  • Last Updated : 09 Dec, 2020

The http.ClientRequest.socket is an inbuilt application programming interface of class ClientRequest within http module which is used to get a Proxy object that acts as a net.Socket.

Syntax:

request.socket

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

Return Value: This property returns a Proxy object that acts as a net.Socket.

Example 1: Filename: index.js



Javascript




// Node.js program to demonstrate the  
// request.socket property
    
// Importing http module 
var http = require('http'); 
    
// Setting up PORT 
const PORT = process.env.PORT || 3000; 
    
// Creating http Server 
var httpServer = http.createServer(
  function(request, response) { 
  
  // Getting proxy socket 
  // by using request.socket
  const value = request.socket;
    
  // Display result
  response.end( value.remoteFamily, 'utf8', () => { 
    console.log("Writing remotefamily of socket..."); 
  
    httpServer.close(() => {
      console.log("server is closed")
    })
  }); 
}); 
    
// Listening to http Server 
httpServer.listen(PORT, () => { 
    console.log("Server is running at port 3000..."); 
});

Run the index.js file using the following command:

node index.js

Output:

Server is running at port 3000...

Now open your browser and go to http://localhost:3000/, you will see the following output on your screen:

IPv6

Now close the browser and you will see the following output on your terminal screen:

Server is running at port 3000...
Writing remotefamily of socket...
server is closed

Example 2: Filename: index.js

Javascript




// Node.js program to demonstrate the  
// request.socket property
    
// Importing http module 
var http = require('http'); 
  
// Request and response handler 
const http2Handlers = (request, response) => { 
    
  // Getting proxy socket 
  // by using request.socket method
  const value = request.socket;
    
  // Display result
  response.end( value.remoteFamily, 'utf8', () => { 
    console.log("Writing remotefamily of socket..."); 
  
    httpServer.close(() => {
        console.log("server is closed")
    })
  });
}; 
    
// Creating http Server 
var httpServer = http.createServer
  (http2Handlers).listen(3000, () => { 
    console.log("Server is running at port 3000..."); 
});

Run the index.js file using the following command:

node index.js

Output:

Server is running at port 3000...

Now open your browser and go to http://localhost:3000/, you will see the following output on your screen:

IPv6

Now close the browser and you will see the following output on your terminal screen:

Server is running at port 3000...
Writing remotefamily of socket...
server is closed

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :