user1582791
user1582791

Reputation: 11

Socket setSoTimeout clarification

I have scenario in which there is server listening on specified ip and port and client which connects to that server. Now I am reading response from server using readline method:

String readme=bs.readline()).   

Here bs is bufferedreader object. I want to know if before reading response if I write this line

socket.setSoTimeout(1000)

and if no response come till 1000 ms

whether socket get timeout and get disconnected or it do not disconnect socket and give empty string in readme.

Upvotes: 1

Views: 7651

Answers (2)

E_net4
E_net4

Reputation: 29983

The socket will not disconnect. Instead, any reading method will throw a SocketTimeoutException that you may wish to catch in your program. The socket can still be used, but readme in such a case will not be defined:

String readme;
try
{
 readme = bs.readline;
// TODO do stuff with readme
}
catch (SocketTimeoutException e)
{
// did not receive the line. readme is undefined, but the socket can still be used
 socket.close(); // disconnect, for example
}

It is assumed in the example that IOExceptions are caught elsewhere or thrown.

The docs explain this behaviour quite well: Socket.setSoTimeout(int)

Upvotes: 1

Nivas
Nivas

Reputation: 18334

Actually neither. A SocketTimeoutException is thrown.

From the docs:

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 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.

Parameters: timeout - the specified timeout, in milliseconds. Throws: SocketException - if there is an error in the underlying protocol, such as a TCP error.

Upvotes: 5

Related Questions