How To: Open Client Socket in Java With Timeout
By Angsuman Chakraborty, Gaea News NetworkTuesday, June 6, 2006
Often we need to create a (client) socket connection in java but we do not want to wait indefinitely for the connection to open. We need a way to timeout socket connections. Two solutions and recommended code.
Previously the only way was to create the socket in a Thread. And then kill the thread if it is running beyond a threshold time limit. This had two problems. First Thread.kill or Thread.suspend are deprecated methods and with good reason. Their availability cannot be ensured in future versions of Java. Secondly the process was clumsy to say the least. Now we have a better method since JDK 1.4.
java.net.Socket supports timeout from JDK1.4 onwards. The following is a sample code to enable socket timeout in Java. In this sample 500 milliseconds is chosen as timeout value.
// Open a socket without any parameters. It hasn’t been binded or connected
Socket sock = new Socket();
// Bind to a local ephemeral port
sock.bind(null);
// Connect to google.com on port 80 with a timeout of 500 milliseconds
sock.connect(new InetSocketAddress(”www.google.com”, 80), 500);
// Your code goes here
// Close the socket.
sock.close();
gpowers01