Node.js http.ServerResponse.socket Api
Last Updated :
05 Apr, 2023
The httpServerResponse.socket is an inbuilt application programming interface of class ServerResponse within http module which is used to get the reference of the underlying socket object.
Syntax:
response.socket
Parameters: This method does not accept any arguments as a parameter.
Return Value: This method returns the reference of the underlying socket object.
Example 1: Filename: index.js
JavaScript
// Node.js program to demonstrate the
// response.socket APi
// Importing http module
const http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
const httpServer = http.createServer(
function (request, response) {
// Getting the reference of the
// underlying socket object
// by using socket API
const value = response.socket;
// display result
// by using end() api
response.end("socket buffersize : "
+ value.bufferSize, 'utf8', () => {
console.log("displaying the result...");
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 below command:
node index.js
Console output:
Server is running at port 3000...
displaying the result...
displaying the result...
server is closed
server is closed
Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser.
socket buffersize : 0
Example 2: Filename: index.js
JavaScript
// Node.js program to demonstrate the
// response.socket APi
// Importing http module
const http = require('http');
// Request and response handler
const http2Handlers = (request, response) => {
// Getting the reference of the underlying socket object
// by using socket API
const value = response.socket;
// Display result
// by using end() api
response.end("Socket local address : "
+ value.localAddress, 'utf8', () => {
console.log("displaying the result...");
// Closing the server
httpServer.close(() => {
console.log("server is closed")
})
});
};
// Creating http Server and listening
// on the given port
const httpServer = http.createServer(
http2Handlers).listen(3000, () => {
console.log("Server is running at port 3000...");
});
Run the index.js file using the below command:
node index.js
Console output:
Server is running at port 3000...
displaying the result...
displaying the result...
server is closed
server is closed
Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser.
socket local address : ::1
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_socket