I'm trying to learn Socket by myself. I'm little bit confused by following text from Oracle website. I have some questions regarding that. Thanks in advance for any clear explanation.
setSoTimeout
public void setSoTimeout(int timeout) throws SocketException
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a
read()
call on theInputStream
associated with this Socket will block for only this amount of time. If the timeout expires, ajava.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.
- What is SO_TIMEOUT?
Socket is the endpoint of a connection. If I say
mySocket.setSoTimeout(2000);
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
What does it mean timeout expire?
What is the option which must be enabled prior to blocking operation?
Infinite Timeout means that the socket does't read anymore?
No, it means that if no data arrives within 2000ms a
SocketTimeoutException
will be thrown.It means the 2000ms (in your case) elapses without any data arriving.
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for
SO_TIMEOUT
time! if it does not get any signal it throw exception! It means that time expired!The JavaDoc explains it very well:
SO_TIMEOUT
is the timeout that aread()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then theread()
call will block until at least 1 byte could be read.