Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 724
Pseudo-Gorgias Avatar asked Sep 03 '12 03:09

Pseudo-Gorgias


People also ask

What is HTTP request in NodeJS?

http module The HTTP options specify the headers, destination address, and request method type. Next, we use http. request to send the data to the server and await the response. The response is stored in the req variable, and upon error, it is logged into the console.

What are the different HTTP methods in node JS?

(A Walkthrough With JavaScript's Fetch API) In this article, we are going to learn the most common HTTP methods(POST, GET, PUT, PATCH, DELETE).

How does node js handle multiple HTTP requests?

How NodeJS handle multiple client requests? NodeJS receives multiple client requests and places them into EventQueue. NodeJS is built with the concept of event-driven architecture. NodeJS has its own EventLoop which is an infinite loop that receives requests and processes them.


1 Answers

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.

like image 78
Matt Ball Avatar answered Sep 21 '22 20:09

Matt Ball