javascript - A little doubt about nodejs handling concurrency
巴扎黑
巴扎黑 2017-05-16 13:39:29
0
3
648

On a whim, I defined a route in express:

var n = 0;

app.get('/', function(req, res){
  console.log(++n);
  setTimeout(function(){
    console.log("ok");
    res.send("ok")
  },6000)

});

The test is as follows, open N browser tabs;
Open the first tab and access localhost:3000/
Open the second tab within 6 seconds and access localhost:3000/
Discover the first A request will not respond to the second access before res.send() ends;
console.log(++n); will not print 2 until res.end is accessed for the first time
= =====================Magic separator========================== ===============
Experiment correction, according to the comments below, the above experiment was opened in different tabs of the same browser,
Using different browsers means that I use Google Chrome to open localhost:3000/, and then use IE browser to open localhost:3000/ within 6 seconds. The previous request will not block the subsequent one, resulting in the following doubt.
The first question, if there are 10,000 users accessing it at the same time within 6 seconds, should I... maintain 10,000 connections? Is this possible? I'm so confused.
Second question, why is it blocked when opening the same browser?

巴扎黑
巴扎黑

reply all(3)
Peter_Zhu

Node’s runtime uses a single-threaded event loop. Wait in setTimeout() 函数是一个阻塞操作,Node 只有一个线程执行 setTimeout()。因此其他的操作都在 队列 in your code.

You can refer to here: http://www.nodebeginner.org/i...

phpcn_u1582

This is a browser problem.
The correct solution is as follows:
https://github.com/tianyk/not...

Code changed according to Pu Ling:

var status = 'ready';


app.get('/', function(req, res){
// 进入之后监听haha事件
  proxy.once('haha', function(x){console.log(x);
      res.send("ok");
  });
  // 打印状态;
  console.log(status);
  // 判断状态,状态为ready,
  if(status == 'ready'){
    status = 'pending';
    console.log(++n);
  setTimeout(function(){
    proxy.emit('haha',"我是啊啊啊啊啊");
    console.log("ok");
    status = 'ready'
  },6000)
  }else{
    console.log("现在是pending状态,我只能等待某个请求返回触发emit")
  }

});

Note here that res is processed in the callback, so that the callback can be distributed to different requesters;
The code I started writing; res is processed in the timer, and a callback is passed in the form of parameters. An error is reported, and I don’t quite understand;

世界只因有你

I don’t understand Nodejs, but I have always heard that Nodejs can handle high concurrency. Let’s take a look.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!