Maxime M.
Maxime M.

Reputation: 377

Java Socket.setSoTimeout() doesn't timeout on connect

I have a problem where I have used setSoTimeout(500) to set a timeout of 0.5 second on the connection and read time delays, but it is not actually working and instead timeouts after about 10 seconds like it usually does with this kind of exception. And yes, the IP is valid in this situation.

java.net.ConnectException: Connection timed out: connect

Here is the code :

try {
    Socket sock = new Socket(ip, 42042);
    sock.setSoTimeout(500);
    BufferedInputStream is = new BufferedInputStream(sock.getInputStream());
    theNames = theNames + is.read() + ";";
    PrintWriter os = new PrintWriter(sock.getOutputStream());
} catch (IOException e) {
    System.out.println(e + " | Le serveur a " + ip + " ne reponds pas.");
}

Upvotes: 1

Views: 2725

Answers (1)

user207421
user207421

Reputation: 311052

Socket.setSoTimeout sets a read timeout. It has nothing to do with connect timeouts. If you want to lower the default connect timeout:

Socket sock = new Socket();
sock.connect(new InetSocketAddress(ip, 42042), timeout);

where timeout is in milliseconds.

Note: The Javadoc says 'a timeout of zero is interpreted as an infinite timeout,' but this is not correct: it is interpreted as the platform default connect timeout, which is around a minute. Infinite timeouts only apply to reads. Note also that you can use connect() to reduce the platform default, but not to increase it.

Half a second is far too short for either a connect timeout or a read timeout.

Upvotes: 6

Related Questions