关于 Socket 设置 setSoTimeout 误用的说明

本文深入解析了setSoTimeout方法的功能及使用场景,并澄清了其并非用于设置连接建立的超时时间,而是指定了读取数据时阻塞等待的最长时限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做网络开发的想必对setSoTimeout这个方法很熟悉,知道是设置的超时事件。但是很多人都认为这个是设置链路的超时时间,但是查看相关文档的此方法的说明:

HttpConnectionParams:

Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. 
A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.

Socket:

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. If the timeout expires,
a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect.
The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

DatagramSocket:

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, 
a call to receive() for this DatagramSocket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised,
though the DatagramSocket is still valid. The option must be enabled prior to entering the blocking operation to have effect.
The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

看文档的详细说明,很显然,这种理解是不对的,不是链接的超时时间。 简单概括起来,应该是:读取数据时阻塞链路的超时时间。

上面Socket的setSoTimeout的文档翻译后的内容为:

setSoTimeout  
public void setSoTimeout(int timeout)  
    throws SocketException启用/禁用带有指定超时值的 SO_TIMEOUT,以毫秒为单位。将此选项设为非零的超时值时,在与此 Socket 关联的 InputStream 上调用 read() 将只阻塞此时间长度。  
    如果超过超时值,将引发 java.net.SocketTimeoutException,虽然 Socket 仍旧有效。选项必须在进入阻塞操作前被启用才能生效。  
    超时值必须是 > 0 的数。超时值为 0 被解释为无穷大超时值。   
参数:  
timeout - 指定的以毫秒为单位的超时值。   
抛出:   
SocketException - 如果底层协议出现错误,例如 TCP 错误。  

最简单的测试验证的方法是:

写一个基于Socket的下载方法,设置setSoTimeout后,下载一个大文件,会发现,下载的时间超过setSoTimeout的值之后,就会失败!!

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值