How to set connect time out on Java sockets

| 3 Comments | 1 TrackBack
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.

1 TrackBack

from Tweets that mention EGOPOLY » Blog Archive » How to set connect time out on Java sockets -- Topsy.com on January 27, 2011 6:34 AM