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] }
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP