The http.ClientRequest.setSocketKeepAlive() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to enable/disable the TCP/IP socket keep alive.
Syntax:
const request.setSocketKeepAlive([enable][, initialDelay])
Parameters: This method takes the following two parameters:
- enable: It is the boolean value that tells whether to keep the socket alive or not.
- initialDelay: It is an optional parameter, is the delay value in milliseconds.
Return Value: This method has nothing to return.
Example 1: Filename-index.js
Javascript
// Node.js program to demonstrate the // request.setSocketKeepAlive() 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'
// Setting the keep alive for the socket
// by using setSocketKeepAlive method
req.setSocketKeepAlive( true );
// Display the result
console.log( "keep alive is enabled for the socket" )
process.exit(0)
}); |
Run the index.js file using the following command:
node index.js
Output:
keep alive is enabled for the socket
Example 2: Filename-index.js
Javascript
// Node.js program to demonstrate the // request.setSocketKeepAlive() 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' ,
});
// Setting the keep alive for the socket
// by using setSocketKeepAlive method
req.setSocketKeepAlive( true );
// Display the result
console.log( "keep alive is enabled for the socket" )
process.exit(0)
}); |
Run the index.js file using the following command:
node index.js
Output:
keep alive is enabled for the socket
Reference: