เมธอด agent.createConnection() เป็นอินเทอร์เฟซที่โมดูล 'http' จัดเตรียมไว้ เมธอดนี้สร้าง socket/stream ที่ใช้สำหรับ HTTP requests สามารถใช้ custom agents เพื่อ override เมธอดนี้เพื่อความยืดหยุ่นมากขึ้น Socket/stream สามารถคืนค่าได้สองวิธี คือ คืน socket/stream โดยตรงจากฟังก์ชันนี้ หรือส่ง socket/stream ไปยัง callback
Syntax
agent.createConnection(options, [callback])
Parameters
ฟังก์ชันข้างต้นรับพารามิเตอร์ดังนี้:
options – รายละเอียดการเชื่อมต่อที่ต้องการสร้าง stream
callback – จะรับ socket connection ที่สร้างจาก agent
ตัวอย่าง
สร้างไฟล์ชื่อ 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);Output
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);Output
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] }