我可以为 InputStream 的 read() 函数设置超时吗? [英] Can I set a timeout for a InputStream's read() function?

查看:113
本文介绍了我可以为 InputStream 的 read() 函数设置超时吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataInputStream that 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.

推荐答案

一般不在 InputStream 上,但可以使用 Socket#setSoTimeout(int) 为所有在 InputStream 上的读取操作设置超时时间套接字本身.

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 的 read() 函数设置超时吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆