Tuesday, May 1, 2012

How to check whether a server started successfully?

Do you know the IP address and port of your server? Then you can use the following code to detect  whether the server has started up. Also if it's not already started the ServerStartupDetector thread will examine the server socket for period of 'TIME_OUT'.

/**
 * This thread tries to detect a server startup, at a given InetAddress and a port
 * combination, within some time period.
 */
public class ServerStartupDetector extends Thread {
    
    /**
     * Time this tries to recover AgentService (in milliseconds).
     */
    private static final long TIME_OUT = 60000;
    
    private InetAddress serverAddress;
    private int port;
    
    public ServerStartupDetector(InetAddress address, int port) {
        serverAddress = address;
        this.port = port;
    }
    
    public void run() {
        
        boolean isServerStarted;
        
        long startTime = System.currentTimeMillis();

        // loop if and only if time out hasn't reached
        while ((System.currentTimeMillis() - startTime) < TIME_OUT) {
            
            try {
                isServerStarted = isServerStarted(serverAddress, port);
                
                System.out.println("Server has started in address: "+serverAddress.getHostAddress()
                                   +" and port: "+port);
                
                if (isServerStarted) {
                    // do something you want
                    break;
                }

                // sleep for 5s before next check
                Thread.sleep(5000);
                
            } catch (Exception ignored){
                //do nothing
            }
        }
        
    }
    
    /**
     * Checks whether the given ip, port combination is not available.
     * @param ip {@link InetAddress} to be examined.
     * @param port port to be examined.
     * @return true if the ip, port combination is not available to be used and false
     * otherwise.
     */
    private static boolean isServerStarted(InetAddress ip, int port) {

        ServerSocket ss = null;

        try {
            ss = new ServerSocket(port, 0, ip);
            ss.setReuseAddress(true);
            return false;

        } catch (IOException e) {
        } finally {

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        return true;

    }

}

You can invoke the above thread as follows.
String ip = "192.168.1.2";
String port = "9443";
        
InetAddress address = InetAddress.getByName(ip);
        
ServerStartupDetector detector = new ServerStartupDetector(
                                       address, Integer.parseInt(port));
        
detector.run();