Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch the SocketTimeoutException

Tags:

java

Say I have a socket variable called SuperSocket is there any way that I can catch the timeout exception ?

       SuperSocket.setSoTimeout(5000);

       catch (SocketTimeoutException e){
        System.out.println("Timeout");
        System.exit(1);
    }
like image 844
Sandeep Johal Avatar asked Dec 06 '12 04:12

Sandeep Johal


People also ask

What is the cause of SocketTimeoutException?

As you may suspect based on the name, the SocketTimeoutException is thrown when a timeout occurs during a read or acceptance message within a socket connection.

What is socket timeout?

socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.


1 Answers

You seem to not understand what setSoTimeout() does and when that exception would be thrown.

From the Javadoc: ( http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html )

public void setSoTimeout(int timeout)
throws SocketException

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is 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.

The only time a SocketTimeoutException can be thrown (and then caught) is when you're doing a blocking read on the Socket's underlying InputStream and no data is received in the specified time (causing the read to ... time out).

superSocket.setSoTimeout(5000);
InputStream is = superSocket.getInputStream();
int i;
try {
    i = is.read();
} catch (SocketTimeoutException ste) {
    System.out.println("I timed out!");
}

Edit to add: There's actually one other time the exception can be thrown, and that's if you're calling the two argument version of Socket.connect() where you supply a timeout.

like image 60
Brian Roach Avatar answered Sep 27 '22 23:09

Brian Roach