socket and setSoTimeout()

后端 未结 2 545
抹茶落季
抹茶落季 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 13:52

    I think,setSotimeout denotes the amount of time a server can wait for a response to read.if timeout value exceeds ,exception will be thrown.

    for example.If you set setSotimeout(4000) to socket,

    Socket will wait for only 4 secs for the receiver to respond,it throws exception after 4 secs.

    It will be useful in slow connection networks or bad servers. It avoids waiting for response.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题