【问题标题】:How NodeJs implements listen() function of http package?NodeJs如何实现http包的listen()函数?
【发布时间】:2021-09-10 02:52:57
【问题描述】:

我试图了解 nodeJs 如何为它的 http 服务器实现 listen()。我尝试查看源代码,但没有太大帮助。

谁能解释一下 listen() 函数是如何永远运行的(是否有无限循环或 setInterval 让它发生?)

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

【问题讨论】:

  • 了解 TCP 如何在套接字级别工作(侦听、绑定、接受)。没有魔法,只是包装你的操作系统已经做的事情。

标签: javascript node.js http asynchronous server


【解决方案1】:

我认为不需要计时器来保持进程运行,因为它是 I/O 事件 - https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#poll

在事件循环的每次运行之间,Node.js 会检查它是否正在等待任何 异步 I/O 或计时器,如果没有则干净地关闭。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2019-07-02
    • 1970-01-01
    • 2021-03-03
    • 2020-02-16
    相关资源
    最近更新 更多