2011-12-18 135 views
0

我差不多是一个节点的新手,并且难以理解http.createServer方法的请求/响应回调的异步方面。阻止HTTP请求/响应回调?

我的理解是,当一个新的请求发出时,anonymouse函数会再次为新客户端运行。

但是在我的测试,我发现,阻塞进程看起来它会影响另一个请求客户端的响应。

我这样说,因为日志消息"A new client!"只有在第一个请求完成后才会发生。

var http = require('http'); 

http.createServer(function(req, res){ 

    console.log("A new client!");  

    var startTime = new Date().getTime(); 
    while (new Date().getTime() < startTime + 4000); 

    res.writeHead(200, {"Content-type" : "text/html"}); 
    res.write("done"); 
    res.end(); 

}).listen("8888"); 

我对localhost:8888在我的浏览器多标签测试。

+0

我怀疑强烈地 “的console.log()” 是* *本身不一定同步,但我不是一个节点的人。我的意思是,调用“console.log()”的可见结果不一定立即可见。这当然是Chrome控制台的工作原理,但我不知道这个事实是否与Node环境真正相关,因为它们明显不同。 – Pointy 2011-12-18 16:43:46

+0

当然你可以通过在日志消息中包含一个请求参数来检查... – Pointy 2011-12-18 16:44:31

+0

[在node.js中意味着什么是非阻塞](http://raynos.org/blog/13/What-it-意思是非节点阻塞。) – Raynos 2011-12-18 17:35:19

回答

1

这与阻塞无关,而是因为Node.js有一个事件循环,这意味着它有事件准备在每次下一个滴答时刻执行。

这些事件are executed in order并且可以有回调。上面的代码启动了一个Web服务器,该服务器具有一个回调,当请求完成时运行回调,然后在回调中显示一条消息(在控制台中)。

您可以查阅一下我以上所说的(约事件顺序为)用下面的代码:

server.js

var counter = 0; 
var http = require('http'); 
http.createServer(function (req, res) { 
    console.log(counter++); 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n'); 
}).listen(1337, "127.0.0.1"); 
console.log('Server running at http://127.0.0.1:1337/'); 

使用Apache Benchmark工具,以模拟100个并发该服务器像这样的连接:

ab -n 100 -c 100 server.js

你会看到你会按顺序获得数字。

资源:

http://www.slideshare.net/brevoortm/nodejs-async-for-the-rest-of-us
http://code.danyork.com/2011/01/25/node-js-doctors-offices-and-fast-food-restaurants-understanding-event-driven-programming/
http://www.yuiblog.com/blog/2010/12/06/video-yuiconf2010-croucher/