Mô tả
Phương thức agent.createConnection() là một giao diện do module http cung cấp. Phương thức này tạo ra một socket/stream có thể sử dụng cho các yêu cầu HTTP. Người dùng có thể sử dụng các agent tùy chỉnh để ghi đè phương thức này để có độ linh hoạt lớn hơn. Một socket/stream có thể được trả về theo hai cách: trả về trực tiếp từ hàm này, hoặc truyền socket/stream này cho callback.
Cú pháp
agent.createConnection(options, [callback])
Tham số
options – Chứa chi tiết kết nối để tạo stream.
callback – Nhận kết nối socket được tạo từ agent.
Ví dụ
Tạo file tên connection.js và sao chép mã dưới đây. Sau khi tạo file, chạy lệnh sau:
node connection.js
connection.js
// Chương trình Node.js demo tạo socket dùng agent.createConnection() // Import module http const http = require('http'); // Tạo agent mới var agent = new http.Agent({}); // Tạo kết nối với agent trên var conn = agent.createConnection; console.log('Kết nối đã được tạo thành công!'); // In chi tiết kết nối console.log('Kết nối: ', conn);Đầu ra
C:\home\node>> node connection.js Kết nối đã được tạo thành công! Kết nối: 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); }Ví dụ khác
// Chương trình Node.js demo tạo socket dùng agent.createConnection() // Import module http const http = require('http'); // Tạo agent mới var agent = new http.Agent({}); // Định nghĩa tùy chọn cho agent const aliveAgent = new http.Agent({ keepAlive: true, maxSockets: 0, maxSockets: 5, }); // Tạo kết nối với alive agent var aliveConnection = aliveAgent.createConnection; // Tạo kết nối mới var connection = agent.createConnection; // In kết nối console.log('Tạo kết nối với agent thành công: ', connection.toString); console.log('Tạo kết nối với alive agent thành công: ', aliveConnection.toString);Đầu ra
C:\home\node>> node connection.js Tạo kết nối với agent thành công: function toString() { [native code] } Tạo kết nối với alive agent thành công: function toString() { [native code] }