如何超时读取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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:56:39  来源:igfitidea点击:

How to timeout a read on Java Socket?

javasocketstimeoutinputstream

提问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.

如果您编写 Java,学习浏览API 文档会很有帮助。在套接字读取的情况下,您可以设置超时选项。

回答by Arie Z.

If this socket was created through a URLConnectionto perform a web request, you can set the read and connect timeouts directly on the URLConnectionbefore 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();
}