Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent application freeze if server unavailable?

InetAddress serverAddr = InetAddress.getByName(serverAddress);
String hostname = serverAddr.getCanonicalHostName();
Socket socket = new Socket(serverAddr, portNumber);
// Freezes before this line if the server is unavailable
socket.setSoTimeout(3000);

Does anyone know how to implement the check of server availability or prevent the freezing?

like image 445
Niko Gamulin Avatar asked Dec 05 '25 05:12

Niko Gamulin


1 Answers

By using the two-argument constructor, you tell Java to connect immediately. What you are looking for is likely

Socket socket = new Socket();
// Configure socket here
socket.connect(new InetSocketAddress(serverAddr, portNumber), 3000);
if (! socket.isConnected()) {
    // Error handling
} else {
    // Use socket
}

This will still block for 3s though. If you want to prevent that, use a thread for the connection.

like image 57
phihag Avatar answered Dec 07 '25 19:12

phihag