Node.js: the relationship between http.Server, http.Agent, sockets and http.request

In docs :

Node.js supports multiple server connections for creating HTTP requests. This feature allows you to transparently issue requests.

The docs further indicate that Node relies on http.globalAgent to make default requests, but you can use your own agent by creating a new http.Agent . Agents are used to "combine sockets" for HTTP requests.

My interpretation of all this is that every time you do http.createServer , by default you get multiple sockets (presumably this is what is meant by “connections”) to make HTTP requests, and these sockets are combined / managed using http.globalAgent .

It’s not clear to me what happens when you create your own http.Agent . Is Agent suitable for "sockets" that were previously managed with http.globalAgent ? Or do you need to create a new socket for your new Agent through agent.createConnection ?

In the corresponding note, if I had to start two servers in the same Node process and subsequently make an http request, for example

 const server1 = http.createServer(function(req, res) { res.end('Hello from server1'); }).listen(3000); const server2 = http.createServer(function(req, res) { res.end('Hello from server2'); }).listen(5000); http.get('/someurl'); 

from which server will the request be executed? Does http.Agent come in here?

+5
source share

All Articles