为什么我只能发送5个请求,如果我不听数据事件?

我发现了一些似乎与这个问题有关系的问题(例如: 为什么node.js一次只能处理6个请求? ),但是我仍然不能理解细节。

以下是我的情况。

首先,服务器的代码:

var express = require ('express'), methodOverride = require('method-override'); var app = express(); app.use(methodOverride()); app.use(function(err, req, res, next) { console.error(err.stack); res.status(500); res.send({ error: err }); }); app.use('/', function(req, res, next) { res.header('Cache-control', 'no-cache'); res.header('Access-Control-Allow-Origin', '*'); next(); }); app.get('/OK/', function (req, res) { console.log(getTimestamp() + ' OK '); res.status(200).send("200"); }); app.listen(22222); function getTimestamp(){ var timestamp = new Date(); return timestamp.toString() + " " + timestamp.getMilliseconds(); } console.log(getTimestamp() + ' Sever started!'); 

然后,客户的代码:

 var http = require('http'); var opt = { method: "GET", host: "localhost", port: 22222, path: "/OK/", headers: { 'Cache-control': 'no-cache' } }; count = 10; function request(){ var req = http.request(opt, function (serverFeedback) { var body = ""; serverFeedback .on('data',function(){}) .on('end', function () { console.log(getTimestamp(), "response END", serverFeedback.statusCode, body); }); }); req.end(); console.log(getTimestamp(), "resuest START"); count--; if(count > 0){ setTimeout(request, 500); } } request(); function getTimestamp(){ var timestamp = new Date(); return timestamp.toString() + " " + timestamp.getMilliseconds(); } 

在节点上运行它们,当然是先运行服务器,客户端会在大约5秒内发送10个请求,一切正常。 喜欢这个: 在这里输入图像描述

但是,如果我删除有关监听客户端中的“数据”事件的代码,如下所示:

 var req = http.request(opt, function (serverFeedback) { var body = ""; serverFeedback //.on('data',function(){}) /* remove the listener*/ .on('end', function () { console.log(getTimestamp(), "response END", serverFeedback.statusCode, body); }); }); 

再次运行,客户端似乎已经在5s发送了10个请求,但实际上,服务器只收到了5个请求: 在这里输入图像描述

正如你所看到的,“结束”事件似乎并没有被触发。

最后,我通过服务器的代码在响应中添加一个头文件:

 app.use('/', function(req, res, next) { res.header('Cache-control', 'no-cache'); res.header('Access-Control-Allow-Origin', '*'); res.header('connection', 'close'); /* add a header about connection */ next(); }); 

重新启动服务器并再次运行客户端: 在这里输入图像描述

现在服务器可以立即收到所有的10个请求,但“结束”事件似乎仍然没有触发。

所以,“数据”事件的监听者似乎已经对http连接产生了一些影响。

任何人都可以解释每个人的细节?

有两件事情正在发生。

首先,当你不“听数据事件”时,响应stream永远不会被完成,所以你所做的http请求永远不会被完成。 这本质上是一个泄漏。 总是消耗你的stream量! 否则,您的stream将无限期地处于“暂停”状态。

第二个是node.js默认的池连接使用默认的代理http://nodejs.org/api/http.html#http_class_http_agent 。 现在,它汇集了5个连接,这就是为什么你看到5个连接的限制。