简体   繁体   中英

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.

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, eg:

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... */
}

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();
}

Yes, there should be an override of Read() that accepts a timeout value. By 'override' I am not suggesting anyone write one, I am pointing out that one of the overrides of the socket methods he is using takes a timeout value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM