java 我可以为 InputStream 的 read() 函数设置超时吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2638283/
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-10-29 22:09:35  来源:igfitidea点击:

Can I set a timeout for a InputStream's read() function?

javaio

提问by Zombies

I have a DataInputStreamthat I obtained from a Socket. Is there any way I can set a timeout for dis.read(...)? Currently I spawn a new thread to do the read. While the parent thread does a thread.join(timeout)to wait before interrupting it. I am aware of nio, but I don't think I want to refactor that much at this point. Thanks.

我有一个DataInputStreamSocket. 有什么办法可以设置超时dis.read(...)吗?目前我生成了一个新线程来进行读取。而父线程thread.join(timeout)在中断它之前会等待。我知道 nio,但我认为此时我不想重构那么多。谢谢。

回答by jarnbjo

Not on the InputStream generally, but you can use Socket#setSoTimeout(int)to set a timeout for all read operations on the socket itself.

通常不在 InputStream 上,但您可以使用它Socket#setSoTimeout(int)为套接字本身的所有读取操作设置超时。