如何使 Java Socket 的读取超时?
我正在尝试从套接字读取项目,我注意到如果套接字流上没有任何内容,它将停留在读取状态并备份我的应用程序。我想知道是否有办法设置读取超时或在套接字中没有任何内容一定时间后终止连接。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您编写 Java,请学习浏览API 文档有帮助。在套接字读取的情况下,您可以 设置超时选项, 例如:
这将导致与套接字关联的
InputStream
在read()
之后抛出SocketTimeoutException
code> 调用阻塞半秒。需要注意的是,SocketTimeoutException
在此类read()
调用引发的异常中是唯一的,因为套接字仍然有效;您可以继续使用它。异常只是一种逃避读取并决定是否需要做不同事情的机制。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, e.g.:
This will cause the
InputStream
associated with the socket to throw aSocketTimeoutException
after aread()
call blocks for one-half second. It's important to note thatSocketTimeoutException
is unique among exceptions thrown by suchread()
calls, because the socket is still valid; you can continue to use it. The exception is only a mechanism to escape from the read and decide if it's time to do something different.如果此套接字是通过
URLConnection
创建的以执行 Web 请求,则可以在读取流之前直接在URLConnection
上设置读取和连接超时:If this socket was created through a
URLConnection
to perform a web request, you can set the read and connect timeouts directly on theURLConnection
before reading the stream:是的,应该重写 Read() 来接受超时值。通过“覆盖”,我并不是建议任何人编写一个,而是指出他正在使用的套接字方法的覆盖之一需要超时值。
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.