套接字和 setSoTimeout() [英] socket and setSoTimeout()

查看:26
本文介绍了套接字和 setSoTimeout()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 socket.setSoTimeout( int ) 方法很困惑.

I am quite confused about socket.setSoTimeout( int ) method.

在我打电话的场景中

 socket.setSoTimeout(4000);
 try{
      string data = input.read();

 }catch (InterruptedIOException e) {

}

当调用 setSoTimeout() 时,它是否会暂停 sokcet 并在 4000 毫秒后恢复?或者它会完全阻止从套接字读取的所有内容,如果在 setSoTimeout 仍处于活动状态时尝试从它读取任何内容,它将引发异常?

when calling setSoTimeout() , does it pauses the sokcet and resumes after 4000 milliseconds? Or it will just completely block all reading from socket and if anything attempts to read from it while setSoTimeout is still active it will throw exception?

如果是最新的,为什么这很有用?根据超时到期后的文档,会自动抛出异常.

If the latest , why is this usefull at all? By documentation after timeout expired the exception is thrown automaticlly.

感谢您的澄清.

推荐答案

Socket.setSoTimeout() 文档的关键部分是:

使用指定的超时时间(以毫秒为单位)启用/禁用 SO_TIMEOUT.将此选项设置为非零超时后,与此 Socket 关联的 InputStream 上的 read() 调用将仅阻塞这段时间.

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time.

这就是说在超过指定的时间时,将阻止对套接字的读取阻塞(这在根据超时"的含义解释时可能会更清楚,如果您熟悉,当然更清楚与系统级套接字接口).它并没有 说读取一定会阻塞那么长时间,这确实是有问题的效用.

This is saying that a read on the socket will be prevented from blocking any longer than the specified time (which is perhaps more clear when interpreted in light of the meaning of "timeout", and is certainly more clear if you are familiar with the system-level socket interface). It does not say that a read is guaranteed to block for that long, which indeed would be of questionable utility.

通过设置超时解决的问题之一是处理不干净的断开连接而不关闭连接的客户端.本地机器无法检测到这种情况已经发生,因此如果没有超时,从连接到此类客户端的套接字读取的尝试将无限期阻塞.

Among the problems solved by setting a timeout is that of handling clients that are uncleanly disconnected without closing the connection. The local machine has no way to detect that that has happened, so without a timeout, an attempt to read from a socket connected to such a client will block indefinitely.

这篇关于套接字和 setSoTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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