简体   繁体   中英

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.

A node http Server instance allows for callbacks to be registered for two type of events, 'request' event, and '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.

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. When stepping through a simple 'hello-world' server in my debugger, I saw that the number of request events outnumber the connection events. 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. 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?).

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? Don't requests basically get queued up on the socket and processed one by one? I understand that Node is asynchronous, but I also thought it behaves in a single-threaded manner.

Thanks in advance!

HTTP is stateless, but it runs over TCP , which is not stateless.

By setting the HTTP request header Connection: keep-alive , it is possible (and often used) to keep the underlying TCP connection open. This is a performance optimization , since TCP connections can be expensive to set up and tear down repeatedly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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