Search code examples
javaandroidtcphttpconnection

ConnectionTimeout versus SocketTimeout


I'm having a problem with a library that I am using. It might be the library or it might be me using it wrong!

Basically, when I do this (Timeout in milliseconds)

_ignitedHttp.setConnectionTimeout(1);  // v short
_ignitedHttp.setSocketTimeout(60000);  // 60 seconds

No timeout exception is generated and it works ok, however, when I do the following,

_ignitedHttp.setConnectionTimeout(60000);  // 60 seconds
_ignitedHttp.setSocketTimeout(1);          // v short

I get a Socket Exception.

So, my question is why can I not simulate a Connection Exception? Am I misunderstanding the difference between a socket and a connection time-out? The library is here (not officially released yet).


Solution

  • Connection Timeout

    A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. If you get an ConnectException, possible reasons are: the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

    Socket Timeout

    A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified time the connection is considered as stalled/broken. Of course this only works with connections where data is received all the time and there are no delays longer than the configured socket timeout.

    By setting socket timeout to 1000 (ms) this would require that every second new data is received (assuming that you read the data block wise and the block is large enough).

    If only the incoming stream stalls for more than a second you are running into a socket timeout.

    This is especially important when HTTP servers process a complex request that requires some time on server side before the HTTP response data is available. If you configure socket timeout to 10000 (10 seconds) but the HTTP server requires 15 seconds after receiving the HTTP request, then you will never get the response as after 10 seconds you will get an SocketTimeoutException (no data is transmitted between reception of the HTTP request until the HTTP response is ready).