zoukankan      html  css  js  c++  java
  • 关于 Socket 设置 setSoTimeout 误用的说明

    做网络开发的想必对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的值之后,就会失败!!

  • 相关阅读:
    事件处理器(eventhandler,或称为事件处理程序)onload
    HTML语言中img标签的alt属性和title属性的作用于区别
    nexus 开机自启动
    idea 上传jar包到nexus
    Spark standalone HA
    spark 性能优化指南
    spark 体验点滴- executor 数量 和task 并行数
    spark 体验点滴-client 与 cluster 部署
    aop concepts
    部署jar到linux ,开机自启动
  • 原文地址:https://www.cnblogs.com/renhui/p/7389820.html
Copyright © 2011-2022 走看看