If client socket opens before the server socket, Java will generate a ConnectionException. So I have to check whether the server is available and keep waiting before executing
socketChannel.open(hostname, port)
in client thread. I've found an related API:
InetAddress.getByName(hostname).isReachable()
However, this still can't tell whether the socket on a specific port is open. I think this problem should be common but I didn't get very useful information from Google and other places.
boolean scanning=true;
while(scanning) {
try {
socketChannel.open(hostname, port);
scanning=false;
} catch(ConnectionException e) {
System.out.println("Connect failed, waiting and trying again");
try {
Thread.sleep(2000);//2 seconds
} catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
This is the code for sonics comment
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