1

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.");
}
2
  • There is no 'input read' here, just a connect. Commented Mar 17, 2015 at 22:45
  • is.read() is an input read if I remember correctly. Commented Mar 18, 2015 at 3:37

1 Answer 1

6

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.

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

2 Comments

This is for an application that searches servers in a local network. 500ms is far enough. I was indeed searching for a connect timeout and not specifically for read timeout. I will try it and give feedback once I will have. Thank you.
@MaximeM. It's not enough if you are experiencing connect timeouts, ipso facto.

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.