如何超时读取Java Socket?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3570762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to timeout a read on Java Socket?
提问by Masterban
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.
我正在尝试从套接字读取项目,我注意到如果套接字流中没有任何内容,它将停留在读取状态并备份我的应用程序。我想知道是否有办法设置读取超时或在套接字中没有任何内容一段时间后终止连接。
回答by Kelly S. French
Yes, there should be an override of Read() that accepts a timeout value. By 'override' I am not suggesting anyone writeone, I am pointing out that one of the overrides of the socket methods he is using takes a timeout value.
是的,应该有一个接受超时值的 Read() 覆盖。通过“覆盖”,我不是建议任何人写一个,我是指出他正在使用的套接字方法的覆盖之一采用超时值。
回答by erickson
If you write Java, learning to navigate the API documentationis helpful. In the case of a socket read, you can set the timeout option.
回答by Arie Z.
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:
如果此套接字是通过 a 创建URLConnection
来执行 Web 请求,则可以直接URLConnection
在读取流之前设置读取和连接超时:
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();
}