Share this page 

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.