Reading from a socket blocks until data are available. If the host is unreachable, your application waits for a long time and you are at the mercy of the underlying operating system to eventually time out.
You can decide what timeout value is reasonable for your particular application. Then, call the
setSoTimeout method to set a timeout value (in milliseconds).
Socket s = new Socket(. . .); s.setSoTimeout(10000); // time out after 10 seconds
If the timeout value has been set for a socket, all subsequent read and write operations throw a
SocketTimeoutException when the timeout has been reached before the operation has completed its work. You can catch that exception and react to the timeout.