Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make client socket wait for server socket

Tags:

java

sockets

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.

like image 929
qweruiop Avatar asked Sep 04 '13 14:09

qweruiop


1 Answers

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

like image 96
Cruncher Avatar answered Oct 13 '22 19:10

Cruncher