EGOPOLY

Topics include: programming, Apple, Unix, gadgets, large-scale web sites and other nerdy stuff.

How to set connect time out on Java sockets

2007-01-23 08:52:11

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 the timeout hasn't been set yet. 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.