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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With