Search code examples
javahttpconnectiontimeout

What is the difference between setReadTimeout() and setConnectTimeout()?


I am sorry if this sounds a very dumb question but googling around for quite sometime did not yield the answer for this question.

I am trying to set the timeout for a connection I am making to a server, where I am using HttpComponentsClientHttpRequestFactory and trying to set the timeout as follows:

clientHttpRequestFactory.setConnectTimeout(timeout);

However, I see that there is another method setReadTimeout(), so I am not sure which is the right one to use to set a timeout before I get a response from the server. The documentation on HttpComponentsClientHttpRequestFactory isn't very clear on this.

Can someone please explain the difference between these two methods?

Edit: What I thought was, if the network is unreliable, I should be setting setConnectTimeout() and setReadTimeout() should be set when the server is unreliable. Is that correct?


Solution

  • ConnectTimeout is the timeout for creating a connection. Let's say you have an unreliable server and you want to wait only 15 seconds before you tell the user that "something is wrong".

    ReadTimeout is the timeout when you have a connection, you're blocked on read() and you want to get an exception if the read blocks for more than timeout.

    Real life examples would be for example to check whether a particular network site is up. The only reliable way to test that is to try to connect to it. You might be able to connect to it, it might give you connection denied, or it would just hang at connection due to network issues. That's where a connection timeout is handy.

    A read timeout can be useful in an application protocol where the clients are required to send a "heartbeat" every so often, to let them know they're still connected (if the server regularly writes back to the client, this isn't necessary, but that's not always the case). You would use a read timeout of the heartbeat time (plus some extra), and if it times out then you can assume the client has been disconnected and close the socket.