node.js中的http.createserver与net.createserver
收藏

我无法理解node.js中的net.createserver和http.createserver之间的区别。

我已经阅读了位于这两个网址的这两种方法的文档 https://nodejs.org/api/net.html#/net_net, https://nodejs.org/api/http.html#/http_class_http_server。

我知道http.createserver创建一个http服务器。但是,文档说net.createserver创建了一个tcp服务器。我知道tcp是http之上的传输协议,并且将http服务器设置为读取http请求标头。我也非常了解node.js中的均匀发射器的概念。但是,我不了解tcp服务器的这一概念以及为什么要在node.js中创建它。上下文是我在“ node.js in action”一书中编写一个聊天应用程序示例。

最佳答案

http.createServer() sets up a server that handles the HTTP protocol, which is indeed transmitted over tcp. net.createServer() creates a server that simply understands when a TCP connection has happened, and data has been transmitted, and so on, but doesn't know anything about whether a valid HTTP request has been received, etc.

If you are writing a web server, favor http.createServer() over net.createServer() as it will save you a lot of work. If you are writing some other kind of server, do not use http.createServer().

    公众号
    关注公众号订阅更多技术干货!