views:

372

answers:

3
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?

+6  A: 

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.

phihag
+3  A: 

I'm going to advise the obvious: Use a seperate thread to do this in. The thread can freeze without freezing the application.

Rolf
A: 

This may be overly simplistic (as it doesn't deal with how to "re-join" the threads after connection is complete - assuming you need to do that.)

Also, if this is going to happen often, you want to use an Executor (thread pool) instead of manually creating your own Thread - thread creation/destruction is expensive.

I also neglect exception handling in this snippet (which isn't completely trivial.)

Runnable runnable = new Runnable() {
   public void run() {
      InetAddress serverAddr = InetAddress.getByName(serverAddress);
      String hostname = serverAddr.getCanonicalHostName();
      Socket socket = new Socket(new InetSocketAddress(serverAddr, portNumber), 3000);
      /* ... do more of your after-connection processing here, assuming it doesn't
       * need to be in the original "dispatch" thread.
       */
   }
};

Thread t = new Thread(runnable);
t.start();
Jared