http header : Connection: Keep-Alive
After reading alot about this , I still can't understand how its working.
wiki :
A keepalive signal can also be used to indicate to Internet infrastructure that the connection should be preserved. Without a keepalive signal intermediate NAT-enabled routers can drop the connection after timeout.
I dont udnerstand :
a Server can have 1,000,000 cuncorrent connections .
John sends a request to the server.
Paul's compter is on the same lan near paul. paul also sends a request to the same server.
John's and paul organization is behind router.
How the hell the server knows how to keep connection alive for both paul and john ?
Also , when john sends request the second time , it "doesnt open a new conneciton" , so how does keep-alive is applied here ?
First of all, TCP/IP connection is not some thin wire that is temporarily connecting two computers. At the end of the day both TCP/IP and UDP are just a series of packets. It's the operating system that pretends you have a connection by putting the IP packets back together in correct order.
Now back to your question. Note that the problem is not really HTTP-specific, all of this works on TCP/IP layer. Say Paul has 192.168.0.100
and John has 192.168.0.101
internal IP addresses while NAT has public 1.2.3.4
address. When Paul connects to some server, his OS uses 192.168.0.100:54321
address (port is chosen randomly by OS). This request hits NAT which remembers that address and forwards request to external server. The external server sees 1.2.3.4:4321
(notice the different port) as the user is behind the NAT so internal IP is not visible.
When the external server (let it be web server) sends a reply, it sends it to 1.2.3.4:4321
. NAT, on the other hand, remembers that 4321
port should be forwarded to 192.168.0.100:54321` - and so it is.
Now imagine John sends request to the same server. This TCP/IP connection is routed through NAT which remember that request from 192.168.0.101:32123
was made. This request is then forwarded using public 1.2.3.4:4322
(notice different port). When response arrives, NAT checks the port if it is 4322
, it routes to 192.168.0.101:32123
(John). Otherwise (on port 4321
) Paul will get his reply.
Note: do not confuse client ephemeral port with server port (80 in HTTP by default).