简体   繁体   English

Node.js HTTP / NET - 连接和请求之间的区别

[英]Node.js HTTP/NET — Difference Between A Connection and A Request

This question concerns general concepts surrounding the tcp/ip protocol, for which there are already good answers on So, but I'm hoping to gain some insight into the particularities of the node.js http/net libraries. 这个问题涉及围绕tcp / ip协议的一般概念,对于它已经有了很好的答案,但是我希望能够深入了解node.js http / net库的特性。

A node http Server instance allows for callbacks to be registered for two type of events, 'request' event, and 'connection', event. 节点http服务器实例允许为两种类型的事件注册回调,'request'事件和'connection',event。 The later of these is inherited from the net library, along with a field '_connections', which counts the number of concurrent connections the server currently has. 其中后者继承自网络库,以及字段“_connections”,它计算服务器当前具有的并发连接数。

Now, it seems to me that since http is a stateless protocol, there should be a 1-1 to correspondence between request and connection events--but this is not the case. 现在,在我看来,由于http是无状态协议,因此请求和连接事件之间应该存在1-1的对应关系 - 但事实并非如此。 When stepping through a simple 'hello-world' server in my debugger, I saw that the number of request events outnumber the connection events. 当我在调试器中单步执行一个简单的“hello-world”服务器时,我看到请求事件的数量超过了连接事件。 I also saw that, even when no calls were being made to the server (and the process was no paused), the .connections field would never zero out. 我也看到了,即使没有对服务器进行调用(并且进程没有暂停),.connections字段也永远不会清零。 Why would the number of requests not equal the number of connections, and why would the server keep a connection open well after the final call to response.end() (when the response buffer is supposed to be flushed and the connections ended?). 为什么请求数量不等于连接数,为什么服务器在最终调用response.end()之后保持连接打开(当响应缓冲区应该被刷新并且连接结束?)。

Also, how could the number of concurrent connections for an http server (that doesn't do anything with keep-alive) ever be higher than 1? 另外,http服务器的并发连接数(对keep-alive没有任何作用)怎么会高于1? Don't requests basically get queued up on the socket and processed one by one? 请求基本上没有在socket上排队并逐个处理? I understand that Node is asynchronous, but I also thought it behaves in a single-threaded manner. 我知道Node是异步的,但我也认为它的行为是单线程的。

Thanks in advance! 提前致谢!

HTTP is stateless, but it runs over TCP , which is not stateless. HTTP是无状态的,但它通过TCP运行,而TCP不是无状态的。

By setting the HTTP request header Connection: keep-alive , it is possible (and often used) to keep the underlying TCP connection open. 通过设置HTTP请求标头 Connection: keep-alive ,可以(并且经常使用)保持底层TCP连接打开。 This is a performance optimization , since TCP connections can be expensive to set up and tear down repeatedly. 这是性能优化 ,因为TCP连接的设置和重复拆卸可能很昂贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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