Java socket FAQ: How do I set the timeout on a Java socket? That is, when I'm trying to read data from a Java socket, and I'm not getting any response from the server, how do I make sure my code doesn't hang up? (It needs to time out after several seconds.)
Answer: Just set the
SO_TIMEOUT on your Java Socket, as shown in the following sample code:
String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket.setSoTimeout(10*1000);
Here's a quote from the
Socket class Javadoc, specifically the Javadoc for this
SO_TIMEOUTwith the specified timeout, in milliseconds. With this option set to a non-zero timeout, a
read()call on the
InputStreamassociated with this
Socketwill block for only this amount of time.
If the timeout expires, a java.net.SocketTimeoutException is raised, though the
Socketis still valid. The option must be enabled prior to entering the blocking operation to have effect.
The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
As shown in the example Java code above, whenever I deal with calls like this socket timeout setting that involve milliseconds, I write my code this way:
Some programmers give me grief about this, but I think it shows my intent, and it's also easier for humans to read
10*1000 than it is something like