เมธอด agent.createConnection() เป็นอินเทอร์เฟซที่จัดเตรียมโดยโมดูล 'http' เมธอดนี้สร้างซ็อกเก็ต/สตรีมที่สามารถใช้สำหรับคำขอ HTTP คุณสามารถใช้ตัวแทนที่กำหนดเองเพื่อแทนที่วิธีนี้เพื่อความยืดหยุ่นที่มากขึ้น ซ็อกเก็ต/สตรีมสามารถส่งคืนได้สองวิธี - โดยส่งคืนซ็อกเก็ต/สตรีมโดยตรงจากฟังก์ชันนี้ หรือโดยการส่งผ่านซ็อกเก็ต/สตรีมนี้ไปยังการโทรกลับ
ไวยากรณ์
agent.createConnection(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\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 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\node>> node connection.js
Succesfully created connection with agent: function toString() { [native code] }
Succesfully created connection with alive agent: function toString() { [native code] }