How to timeout a read on Java Socket?

2019-01-19 10:20发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

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.