socket and setSoTimeout()

后端 未结 2 578
抹茶落季
抹茶落季 2021-01-28 13:11

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

In scenario when i call

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


        
2条回答
  •  天命终不由人
    2021-01-28 14:01

    The key part of the documentation for Socket.setSoTimeout() is:

    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.

提交回复
热议问题