Node.js 中的 agent.createConnection() 方法
该方法是“http”模块提供的接口。此方法生成可用于HTTP请求的套接字/流。可以使用自定义代理来覆盖此方法以获得更大的灵活性。可以通过两种方式返回套接字/流-直接从此函数返回套接字/流,或将此套接字/流传递给回调。agent.createConnection()
语法
agent.createConnection(options, [callback])
参数
上述函数可以接受以下参数-
options –这些选项将包含必须为其创建流的连接详细信息。
回调 -这将从代理接收创建的套接字连接。
示例
创建一个具有该名称的文件-connection.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示-
node connection.js
连接.js
//Node.js程序演示socket的创建 //使用agent.createConnection()方法 //导入http模块 const http = require('http'); //创建新代理 var agent = new http.Agent({}); //与上述代理建立连接 var conn = agent.createConnection; console.log('Connection is succesfully created !'); //打印连接详细信息 console.log('Connection: ', conn);输出结果
C:\home\node>> 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程序演示socket的创建 //使用agent.createConnection()方法 //导入http模块 const http = require('http'); //创建新代理 var agent = new http.Agent({}); //定义代理选项 const aliveAgent = new http.Agent({ keepAlive: true, maxSockets: 0, maxSockets: 5, }); //创建与活动代理的连接 var aliveConnection = aliveAgent.createConnection; //创建新连接 var connection = agent.createConnection; //打印连接 console.log('Succesfully created connection with agent: ', connection.toString); console.log('Succesfully created connection with alive agent: ', aliveConnection.toString);输出结果
C:\home\node>> node connection.js Succesfully created connection with agent: function toString() { [native code] } Succesfully created connection with alive agent: function toString() { [native code] }