Node.js agent.createConnection() 方法
Node.js HTTP API 是低级的,因此它可以支持 HTTP 应用程序。为了访问和使用 HTTP 服务器和客户端,我们需要调用它们(通过 'require('http')')。 HTTP 消息头以 JSON 格式表示。
agent.createConnection() (在 v0.11.4 中添加)方法是 'Http '模块的内置应用程序编程接口,用于生成进一步用于HTTP请求的套接字或流,默认情况下,它与net.createConnection() 。它返回< net.Socket > 类的一个实例,它是< stream.Duplex > 的子类。可以通过从此函数返回套接字/流或将套接字/流传递给回调来提供套接字或流。
句法:
agent.createConnection(options[, callback])
参数:该函数接受上面提到的两个参数,如下所述:
options < Object > :它是包含连接详细信息的任何
Callback < 函数 > :是一个回调< 函数>,接收创建的socket。
返回值
下面的例子说明了在 Node.js 中agent.createConnection(options[, callback])方法的使用。
示例 1:文件名:index.js
// Node.js program to demonstrate the
// agent.createConnection() method
// Importing http module
const http = require('http');
// Creating new agent
var agent = new http.Agent({});
// Creating new connection
var createConnection = agent.createConnection;
console.log('Connection successfully created...');
// Printing that connection
console.log('Connection: ', createConnection);
输出:
Connection successfully created...
Connection: [Function: connect]
示例 2:文件名:index.js
// Node.js program to demonstrate the
// agent.createConnection() method
// Importing http module
const http = require('http');
var agent = new http.Agent({});
// Creating new agent
const aliveAgent = new http.Agent({
keepAlive: true,
maxSockets: 0, maxSockets: 5,
});
// Creating new agent
var agent = new http.Agent({});
// Creating new connection
var createConnection = aliveAgent.createConnection;
// Creating new connection
var createConnection = agent.createConnection;
console.log('Connection successfully created...');
// Printing the connection
console.log(createConnection);
console.log('Connection successfully created...');
// Printing the connection
console.log('Connection: ', createConnection);
使用以下命令运行index.js文件:
node index.js
输出:
Connection successfully created...
Connection: [Function: connect]
Connection successfully created...
Connection: [Function: connect]
参考: https://nodejs.org/api/http.html#http_agent_createconnection_options_callback