为什么我的请求在循环中暂停?

我正在尝试从我正在阅读的书“学习节点2012”中检验一些示例。 而我的2000请求testing服务器的应用程序正在暂停。 testing者在5个请求之后暂停,并且在一定时间间隔之后再发送5个。 为什么暂停? 我怎样才能解决这个问题?

服务器代码:

var http = require('http'); var fs = require('fs'); // write out numbers var counter = 0; function writeNumbers(res) { for (var i = 0; i < 100; i++) { counter++; res.write(counter.toString() + '\n'); } } // create the http server http.createServer( function(req, res) { var query = require('url').parse(req.url).query; var app = require('querystring').parse(query).file + ".txt"; // content header res.writeHead(200, { 'Content-Type': 'text/plain' } ); // write out numbers writeNumbers(res); // timer to open file and read contents setTimeout(function() { console.log('opening ' + app); // open and read in file contents fs.readFile(app, 'utf8', function(err, data) { if (err) res.write('Could not find or open file for reading\n'); else res.write(data); res.end(); }); }, 2000); }).listen(3000); console.log('Server is running on port 3000'); 

垃圾邮件testing代码:

 var http = require('http'); // the url we want, plus the path and options we need var options = { host: 'localhost', port: 3000, path: '/?file=secondary', method: 'GET' }; var processPublicTimeline = function(response) { // finished? ok, write the data to a file console.log('finished request'); }; for (var i = 0; i < 2000; i++) { // make the request, and then end it, to close the connection http.request(options, processPublicTimeline).end(); } 

虽然这肯定有一些关系为什么node.js一次只处理六个请求?

这也是因为您正在使用timeOut来调用res.end()来closures连接/响应,从而移动到队列中的下一个连接。

你应该思考这些types的事情,而不是使用timeOut s,而是使用callBacks

所以你的两个主要块的代码可能更像是:

 var counter = 0; function writeNumbers(res, callBack){ // notice callBack argument for (var i = 0; i < 100; i++){ counter++; res.write(counter.toString() + '\n'); } // execute callBack (if it exists) if(callBack && typeof callBack === "function") callBack(); } http.createServer( function (req, res){ var query = require('url').parse(req.url).query; var app = require('querystring').parse(query).file + ".txt"; res.writeHead(200, { 'Content-Type': 'text/plain' } ); writeNumbers(res, function(){ // Notice this function which is passed as a callBack argument for writeNumbers to evaluate. // This executes when the main writeNumbers portion finishes. console.log('opening ' + app); fs.readFile(app, 'utf8', function(err, data) { if (err) res.write('Could not find or open file for reading\n'); else res.write(data); res.end(); }); }); }).listen(3000); 

注意你的writeNumbers函数现在需要一个callBack参数来执行完成,当你在服务器的对象中调用它的时候,你传递一个函数作为callBack参数。 这是node.js / javascript应用程序中经常使用的核心模式之一。

这意味着你不会等待一段时间来执行结束你的请求响应,而是在处理你的响应时结束,并立即移动到下一个连接。 这可能比2秒( timeOut的数量)更快。 所以你应该看到你的连接处理得更快。

因为(正如有人在你的评论中指出的那样)你的系统一次只能处理几个开放的TCP连接,所以你想尽可能快地通过你的连接。 利用callback链可以帮助您在按照特定顺序执行操作时执行该操作,或者在执行其他操作之前需要等待某些过程完成,而不用用timeOut进行猜测。

希望这可以帮助!