Node.js http.ClientRequest.setSocketKeepAlive() Method
Last Updated :
12 Apr, 2021
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
const http = require( 'http' );
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type' : 'text/plain' });
res.end( 'okay' );
});
server.listen(3000, '127.0.0.1' , () => {
const options = {
port: 3000,
host: '127.0.0.1' ,
headers: {
'Connection' : 'Upgrade' ,
'Upgrade' : 'websocket'
}
};
const req = http.request(options);
req.host = '127.0.0.1'
req.setSocketKeepAlive( true );
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
const http = require( 'http' );
http.createServer((req, res) => { }).listen(3000, '127.0.0.1' , () => {
const req = http.request({
port: 3000,
host: '127.0.0.1' ,
});
req.setSocketKeepAlive( true );
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:
https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_setsocketkeepalive_enable_initialdelay
Share your thoughts in the comments
Please Login to comment...