[英]When data is added to the firestore, I want to listen with onSnapshot so that the data can be called automatically, but I don't know how to use
[英]why I can only send 5 request if I don't listen the data event?
我发现一些问题似乎与此问题相关(例如: 为什么node.js一次只能处理六个请求? ),但我仍然无法理解细节。
以下是我的情况。
首先,服务器的代码:
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);
});
});
再次运行,客户端似乎在5秒钟内发送了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个请求,但是“ end”事件似乎仍然没有触发。
因此,似乎“数据”事件上的侦听器已对http连接产生了一些影响。
谁能为每个人解释细节?
两件事正在发生。
首先,当您不“收听数据事件”时,响应流将永远不会完成,因此您发出的http请求也永远不会完成。 这本质上是泄漏。 总是消耗你的流!!! 否则,您的流将无限期处于“已暂停”状态。
第二个是默认情况下,node.js使用默认代理http://nodejs.org/api/http.html#http_class_http_agent来池化连接。 现在,它汇集了5个连接,这就是为什么您看到5个连接的限制的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.