當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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])

參數:此函數接受上述和以下描述的兩個參數:

  • 選項<Object>:它是包含連接詳細信息的任何<Object>或JSON數據。



  • 回調<Function>:這是一個回調<function>,它接收創建的套接字。

返回值<stream.Duplex>:它返回可讀和可寫的雙工流。

以下示例說明了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




相關用法


注:本文由純淨天空篩選整理自vikas_g大神的英文原創作品 Node.js agent.createConnection() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。