Java Reference
In-Depth Information
SO_TIMEOUT
SO_TIMEOUT is the amount of time, in milliseconds, that accept() waits for an in‐
coming connection before throwing a java.io.InterruptedIOException . If
SO_TIMEOUT is 0, accept() will never time out. The default is to never time out.
Setting SO_TIMEOUT is uncommon. You might need it if you were implementing a
complicated and secure protocol that required multiple connections between the client
and the server where responses needed to occur within a fixed amount of time. However,
most servers are designed to run for indefinite periods of time and therefore just use
the default timeout value, 0 (never time out). If you want to change this, the setSoTi
meout() method sets the SO_TIMEOUT field for this server socket object:
public void setSoTimeout ( int timeout ) throws SocketException
public int getSoTimeout () throws IOException
The countdown starts when accept() is invoked. When the timeout expires, ac
cept() throws a SocketTimeoutException , a subclass of IOException . You need to set
this option before calling accept() ; you cannot change the timeout value while ac
cept() is waiting for a connection. The timeout argument must be greater than or equal
to zero; if it isn't, the method throws an IllegalArgumentException . For example:
try ( ServerSocket server = new ServerSocket ( port )) {
server . setSoTimeout ( 30000 ); // block for no more than 30 seconds
try {
Socket s = server . accept ();
// handle the connection
// ...
} catch ( SocketTimeoutException ex ) {
System . err . println ( "No connection within 30 seconds" );
}
} catch ( IOException ex ) {
System . err . println ( "Unexpected IOException: " + e );
}
The getSoTimeout() method returns this server socket's current SO_TIMEOUT value.
For example:
public void printSoTimeout ( ServerSocket server ) {
int timeout = server . getSoTimeOut ();
if ( timeout > 0 ) {
System . out . println ( server + " will time out after "
+ timeout + "milliseconds." );
} else if ( timeout == 0 ) {
System . out . println ( server + " will never time out." );
} else {
System . out . println ( "Impossible condition occurred in " + server );
System . out . println ( "Timeout cannot be less than zero." );
}
}
Search WWH ::




Custom Search