Have timeout on socket connectionTag(s): Networking

[JDK11]
ServerSocket server = new ServerSocket(port);
// timeout after 60 seconds
server.setSoTimeout(60000);
try {
  Socket socket=server.accept();
  }
catch ( java.io.InterruptedIOException e ) {
  System.err.println( "Timed Out (60 sec)!" );
  }
This is true for READ operation too. Since READ operation blocks as long necessary it may be wise to use the setSoTimeout() method. Note that when the TIMEOUT expires, an InterruptException is thrown. However, the socket is still connected even though the Exception was raised.


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]