Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent HTTP connection Java

I know that when using HttpURLConnection Java tries to reuse the same TCP connection for multiple requests to server unless there is a limitation from server side. Indeed, when I see wireshark log, one of the requestHeaders of HTTP header is Connection: keep-alive. But when server returns data I see a TCP [FIN,ACK] packet being sent back to server from my side.

How exactly does this reuse the tcp connection?

like image 225
astralmaster Avatar asked Oct 20 '22 18:10

astralmaster


1 Answers

In HTTP 1.0 there are no official specifications regarding the idea of persistent connections. For a persistent connection to work the client requests the connection to be kept opening by the addition of the Connection header as such:

Connection: Keep-Alive

If the server decides that the connection should be kept-alive (i.e. not closed) it to should respond with the header:

Connection: Keep-Alive

followed by keeping the connection alive for whatever defined period of time it chooses. Please note that the keep alive "feature" is not a official protocol feature of HTTP 1.0 and thus servers are not required to facilitate the client's request should the client request it.

In HTTP 1.1 it became implicit of persistent connections so if you see this happening on a server responding with HTTP/1.1 headers suspect that the server isn't adhering to HTTP 1.1 standards (unless the server explicitly responds with a Connection header with the value of Close).

In any case however there is a timeout period as defined by the server in which subsequent requests should be sent in by or else the connection is dropped. This is to prevent a spam of unclosed connections should clients drop without properly closing the connection.

The Java HttpURLConnection object attempts to reuse the TCP connection but upon failure will simply fall back to creating a new TCP connection.

like image 84
initramfs Avatar answered Oct 23 '22 09:10

initramfs