I'm trying to figure out how HTTP keep-alive works. According to the docs, all requests by default use the global http.Agent (or https.Agent), which pools connections per origin. Consider the following code; it starts a TCP server that provides a basic response to HTTP requests and does not close the socket.
```
var http = require('http'),
net = require('net');
net.createServer(function(conn) {
console.log('[CONNECT]');
conn.on('data', function(chunk) {
console.log(chunk.toString());
conn.write( 'HTTP/1.1 200 OK\r\n' +
'Content-Length: 5\r\n' +
'Connection: keep-alive\r\n' +
'\r\n' +
'Hello');
});
}).listen(4000);
http.get(origin + '/first', function(response) {
response.on('data', function() { });
response.on('end', function() {
http.get(origin + '/third', function(response) { });
});
});
http.get(origin + '/second', function(response) { });
```
The 'first' and 'second' and requests want to happen in parallel, so I would expect them to use separate TCP connections, and indeed they do. However, the 'third' request, which happens once 'first' is complete, is sent over its own TCP connection rather than reusing the one used for 'first'.
Is it possible to make sequential requests reuse the TCP connection, and if so how?
Many thanks,
James
--
James Coglan
http://jcoglan.com
+44 (0) 7771512510