How to timeout a read on Java Socket?

2019-01-19 10:21发布

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.

3条回答
Summer. ? 凉城
2楼-- · 2019-01-19 11:01

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.

查看更多
在下西门庆
3楼-- · 2019-01-19 11:09

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.

查看更多
Melony?
4楼-- · 2019-01-19 11:17

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();
}
查看更多
登录 后发表回答