简体   繁体   中英

Blocking on http request/response callback?

I'm more or less a node newbie and having a bit of difficulty understanding the the asynchronism aspect of the request / response callback for the http.createServer method.

My understanding was that when a new request is made the anonymouse function would run again for the new client.

However in my testing I've found that the blocking process looks like it effects the response for another requesting client.

I say this because the log message "A new client!" only apears after the first request has finished.

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");

I am testing on localhost:8888 with multiple tabs in my browser.

That's not related to blocking, but to the fact that Node.js has an event loop, which means it has events to ready to be executed on the next tick each time.

These events are executed in order and can have callbacks. Your code above starts a web server that has a callback which is run when the request has been made, and after that in the callback you display a message (in the console).

You can check what I've said above (about events being in order) with the following code:

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/');

Use the Apache Benchmark tool to simulate 100 concurrent connections for that server like so:

ab -n 100 -c 100 server.js

You'll see that you'll get the numbers in order.

Resources:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM