isf*_*ior 4 javascript http node.js
我正在尝试使用http.Agent({ keepAlive: true})onhttp.request来保持连接打开以供将来的请求。
我创建了一个简单的服务器来记录每个新连接,但是当我运行request.js时,服务器会记录两个新连接。
如何将 HTTP keep-alive 与 Node.js 本机模块一起使用?
请求.js:
const http = require("http");
const agent = new http.Agent({
keepAlive: true
});
var req1 = http.request({
agent: agent,
method: "GET",
hostname: "localhost",
port: 3000
}, function (res1) {
console.log("REQUEST_1");
var req2 = http.request({
agent: agent,
method: "GET",
hostname: "localhost",
port: 3000
}, function (res2) {
console.log("REQUEST_2");
});
req2.end();
});
req1.end();
Run Code Online (Sandbox Code Playgroud)
服务器.js:
const http = require('http');
var server = http.createServer(function (req, res) {
res.end('OK');
console.log("REQUEST");
})
server.on('connection', function (socket) {
console.log("NEW CONNECTION");
})
server.listen(3000);
Run Code Online (Sandbox Code Playgroud)
输出:
NEW CONNECTION
REQUEST
NEW CONNECTION
REQUEST
Run Code Online (Sandbox Code Playgroud)
设置maxSockets选项如下:
const agent = new http.Agent({
keepAlive: true,
maxSockets: 1
});
Run Code Online (Sandbox Code Playgroud)
默认maxSockets设置为Infinity- https://nodejs.org/api/http.html#http_new_agent_options
节点 v10 上的完整示例
const http = require("http");
const agent = new http.Agent({
keepAlive: true,
maxSockets: 1
});
var req1 = http.request({
agent: agent,
method: "GET",
hostname: "localhost",
port: 3000
}, function (res1) {
console.log("REQUEST_1");
res1.on('data', function () {
console.log("REQUEST_1 data");
});
res1.on('end', function () {
console.log("REQUEST_1 end");
});
var req2 = http.request({
agent: agent,
method: "GET",
hostname: "localhost",
port: 3000
}, function (res2) {
console.log("REQUEST_2");
res2.on('data', function () {
console.log("REQUEST_2 data");
});
res2.on('end', function () {
console.log("REQUEST_2 end");
});
});
req2.end();
});
req1.end();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10251 次 |
| 最近记录: |