agent.createConnection() 方法在 Node.js 中
agent.createConnection() 方法是 "http" 模块提供的接口。此方法产生可用于 HTTP 请求的套接字/流。我们可以使用自定义代理来覆盖此方法以提高灵活性。套接字/流可以通过两种方式返回 - 直接从此函数返回套接字/流,或将此套接字/流传递给回调函数。
语法
agent.createConnection(options, [callback])
参数
上述函数可接受以下参数 -
options – 这些选项将包含必须为其创建流的连接详细信息。
callback – 这将从代理接收创建的套接字连接。
示例
创建名为 connection.js 的文件并复制以下代码段。创建该文件后,使用以下命令运行此代码,如下例所示 -
node connection.js
connection.js
// Node.js program to demonstrate the creation of socket // using agent.createConnection() method // Importing the http module const http = require('http'); // Creating a new agent var agent = new http.Agent({}); // Creating connection with the above agent var conn = agent.createConnection; console.log('Connection is succesfully created !'); // Printing connection details console.log('Connection: ', conn);
输出
C:\home
ode>> node connection.js Connection is succesfully created ! Connection: function connect(...args) { var normalized = normalizeArgs(args); var options = normalized[0]; debug('createConnection', normalized); var socket = new Socket(options); if (options.timeout) { socket.setTimeout(options.timeout); } return socket.connect(normalized); }
示例
我们来看另一个示例。
// Node.js program to demonstrate the creation of socket // using agent.createConnection() method // Importing the http module const http = require('http'); // Creating a new agent var agent = new http.Agent({}); // Defining options for agent const aliveAgent = new http.Agent({ keepAlive: true, maxSockets: 0, maxSockets: 5, }); // Creating connection with alive agent var aliveConnection = aliveAgent.createConnection; // Creating new connection var connection = agent.createConnection; // Printing the connection console.log('Succesfully created connection with agent: ', connection.toString); console.log('Succesfully created connection with alive agent: ', aliveConnection.toString);
输出
C:\home
ode>> node connection.js Succesfully created connection with agent: function toString() { [native code] } Succesfully created connection with alive agent: function toString() { [native code] }
广告