Problem description
This exception occurs when an attempt to establish a socket connection or read data times out.
Solution
SocketTimeoutException occurs in accept() and read() if a socket connection is not established after the timeout period defined for the server or client is reached. We recommend that you set a reasonable timeout period for socket connections and catch and handle the SocketTimeoutException.
Sample code
Server:
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8111);
serverSocket.setSoTimeout(10000);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client said :"+ inputReader.readLine());
} catch (SocketTimeoutException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}Client:
@Override
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000);
log.info("Response Code: " + con.getResponseCode());
} catch (SocketTimeoutException e) {
System.out.println("SocketTimeoutException"+e.getMessage());
} catch (IOException e) {
System.out.println("IOException"+e.getMessage());
} catch (Exception e) {
System.out.println("Exception"+e.getMessage());
}
}