一个nodejs开两个监听端口,执行时是否是两个线程?
因为刚接触nodejs不久,以上问题,困惑了我很久,一直想不明白。既然想不明白就直接上代码验证一下,看结果是什么样。
var express1 = require('express');
var express2 = require('express');
var app1 = express1();
var app2 = express2();
var port1 = 6211;
var port2 = 6212;
app1.listen(port1);
console.log("app1 server is listening on " + port1);
app2.listen(port2);
console.log('app2 server is listening on ' + port2);
app1.use('/', (req, res, next)=>{
console.log('app1 visit');
res.send('ok1');
next();
});
app2.use('/', (req, res, next)=>{
console.log('app2 visit');
res.send('ok2');
next();
});
app1.use('/loop', (req, res, next)=>{
var date1 = new Date();
console.log(date1);
var date2 = new Date();
date2.setMinutes(49);
date2.setSeconds(0);
console.log(date2);
while (date2 - date1 > 0){
console.log('app1 enter loop :' + date1);
date1 = new Date();
}
next();
});
如上面的代码,另外开了两个终端,试验6211 和6212两个端口。
在17:46的时候执行http://localhost:6211/loop
在17:47时执行http://localhost:6212
设定/loop 中运行到17:49结束。
如下,结果出来了,17:47的6212监听进入数据,要等到/loop 17:49
while 循环后才执行,因此证明了这两个端口是串行的!
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app1 enter loop :Thu Mar 29 2018 17:48:58 GMT+0800 (CST)
app2 visit
打印结果如上所示,这就证明了nodejs一个进程监听的两个端口是串行的,
这也正好印证了nodejs是单线程这个结论。