📜  Node.js http.ClientRequest.setSocketKeepAlive() 方法

📅  最后修改于: 2022-05-13 01:56:27.699000             🧑  作者: Mango

Node.js http.ClientRequest.setSocketKeepAlive() 方法

http.ClientRequest.setSocketKeepAlive()是 HTTP 模块中 ClientRequest 类的内置应用程序编程接口,用于启用/禁用 TCP/IP 套接字保持活动。

句法:

const request.setSocketKeepAlive([enable][, initialDelay])

参数:该方法采用以下两个参数:

  • enable:它是一个布尔值,它告诉我们是否让套接字保持活动状态。
  • initialDelay:它是一个可选参数,是以毫秒为单位的延迟值。

返回值:此方法没有任何返回值。

示例 1:文件名-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)
});


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)
});


使用以下命令运行index.js文件:

node index.js

输出:

keep alive is enabled for the socket

示例 2:文件名-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)
});

使用以下命令运行index.js文件:

node index.js

输出:

keep alive is enabled for the socket

参考:

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