Have timeout on socket connectionTag(s): Networking
About cookies on this site
We use cookies to collect and analyze information on site performance and usage,
to provide social media features and to enhance and customize content and advertisements.
[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.