5

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I just checked my log again, and the server does seem to respond with HTTP/1.1 OK response, however the Connection header has value of: Close. I suppose the server is configured that way.
@astralmaster Keeping the connection open does facilitate more efficient content transmission but also leaves servers vulnerable to DoS attacks as multiple persistent connections can be opened (wasting server resources) which can quickly overwhelm the server. Disabling persistent connections can almost be seen as a safety measure in this case (though not exactly a very effective one).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.