Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout a read on Java Socket?

I'm trying to read items from a socket and I notice that if there is nothing on the stream of the socket it will stay at the read and back up my application. I wanted to know if there was a way to set a read timeout or terminate the connection after a certain amount of time of nothing in the socket.

like image 353
Masterban Avatar asked Aug 25 '10 22:08

Masterban


2 Answers

If you write Java, learning to navigate the API documentation is helpful. In the case of a socket read, you can set the timeout option, e.g.:

socket.setSoTimeout(500);

This will cause the InputStream associated with the socket to throw a SocketTimeoutException after a read() call blocks for one-half second. It's important to note that SocketTimeoutException is unique among exceptions thrown by such read() calls, because the socket is still valid; you can continue to use it. The exception is only a mechanism to escape from the read and decide if it's time to do something different.

while (true) {
    int n;
    try {
        n = input.read(buffer);
    catch (SocketTimeoutException ex) {
        /* Test if this action has been cancelled */
        if (Thread.interrupted()) throw new InterruptedIOException();
    }
    /* Handle input... */
}
like image 59
erickson Avatar answered Oct 28 '22 23:10

erickson


If this socket was created through a URLConnection to perform a web request, you can set the read and connect timeouts directly on the URLConnection before reading the stream:

InputStream createInputStreamForUriString(String uriString) throws IOException, URISyntaxException {
    URLConnection in = new URL(uriString).openConnection();
    in.setConnectTimeout(5000);
    in.setReadTimeout(5000);
    in.setAllowUserInteraction(false);
    in.setDoInput(true);
    in.setDoOutput(false);
    return in.getInputStream();
}
like image 26
Arie Z. Avatar answered Oct 28 '22 23:10

Arie Z.