How to set connect time out on Java sockets

You’d think this would be incredibly obvious, and maybe it is. Maybe I’m an idiot. Whether or not I am, I recently was trying to figure out why Socket connect timeouts weren’t working. Here was the code that didn’t work:

Socket sock = new Socket("hostname", port);
sock.setSoTimeout(5000);

This was supposed to set a connect timeout of 5 seconds. But what actually happens is that the constructor initiates the connect(), when that the timeout hasn’t been set. So you get the default timeout, which is like 75,000 centuries. The right way to do it:

SocketAddress sockaddr = new InetSocketAddress(host, port);
Socket sock = new Socket();
sock.connect(sockaddr, 5000);

And now everything is working. Yay.

3 Responses to “How to set connect time out on Java sockets”

  1. oscar Says:

    Thanks so much,I get the same problem and I think like you

  2. Matias G Rodriguez Says:

    How to do this on JDK 1.3 where there is no such a method?

    Regards.
    Matias G Rodriguez

  3. billo Says:

    As far as I know, you can’t do it in 1.3. The only way I can imagine that you could is to start a timer thread, and then send an interrupt to the socket-opening thread, catching interrupted exception. But I don’t know if that would actually break into a socket connect() call.

    1.3 is pretty old; I know you probably don’t have a choice, but getting to a more modern JVM would have many other benefits.