21

I want to check if server application is available. After server is started I want to stop checking until the server changes status. How to do that with my code:

 private static final String SERVER_ADDRESS = "192.144.10.10";
    private static final int TCP_SERVER_PORT = 8890;
    private static boolean connected = false;
    static Socket s;

    public static void main(String[] args) {

    Timer timer = new Timer();
    timer.schedule(task, 01, 5001); }  

static TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (connected == false)
            {
            System.out.println(hostAvailabilityCheck());
            }
        }
    };

    public static boolean hostAvailabilityCheck()
    { 

        boolean available = true; 
        try {               
            if (connected == false)
            { (s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT)).close();    
            }               
            } 
        catch (UnknownHostException e) 
            { // unknown host 
            available = false;
            s = null;
            } 
        catch (IOException e) { // io exception, service probably not running 
            available = false;
            s = null;
            } 
        catch (NullPointerException e) {
            available = false;
            s=null;
        }


        return available;   
    } 

Is there any better way to solve this?

4
  • 1
    the static field connected seems to be pretty useless, because you never change it Commented Jun 17, 2013 at 12:23
  • Well, this will check whether the host/port pair is available, but it will not check anything functional... It could be that the serving software behind is fubar and always returns 500 for HTTP, for instance Commented Jun 17, 2013 at 12:27
  • This could help you stackoverflow.com/questions/9552743/… Your URL(URL_TO_APPLICATION) could be SERVER_ADDRESS + TCP_SERVER_PORT also see this coderanch.com/t/205709/sockets/java/check-server Commented Jun 17, 2013 at 12:27
  • What are you checking, the availability of the physical server, or an application running on it, like Tomcat? Commented Jun 17, 2013 at 14:14

5 Answers 5

36

The check method can be rewritten as follows (Java 7 and later):

public static boolean hostAvailabilityCheck() { 
    try (Socket s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT)) {
        return true;
    } catch (IOException ex) {
        /* ignore */
    }
    return false;
}

In addition to simplifying the exception handling, this eliminates a pesky Socket leak. (If you are concerned with the time taken to do this check, then set a connection timeout before attempting to connect: see Setting a timeout for socket operations)

But the problems with this approach are many-fold:

  • It only tests that something is listening for connections. If your service is behind a proxy ... or is managed by something like the inetd service ... then the accepted connections don't mean your service is actually working.

  • This is going to cause your service to "see" connections that close down without sending a request. So you'd better code your service to deal with this "gracefully".

  • Doing this repeatedly adds to network and server load.

  • If you set a short timeout because you don't want the test to "freeze", then you risk setting it too short and judging the host to be down when it isn't.


After server is started I want to stop checking until the server changes status

That is next to impossible. The reason is that you won't be able to tell whether the server has "changed status" without checking. Or at least, you won't be able to do this without implementing an elaborate status notification service where the server calls the client to tell it is changing status. (And if "change status" includes "die" or "lost network connection", then you won't be able to make that notification reliably.)

Sign up to request clarification or add additional context in comments.

Comments

6
public static boolean hostAvailabilityCheck() { 
    try (Socket s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT)) {
        return true;
    } catch (IOException ex) {
        /* ignore */
    }
    return false;
}

working, but the problem is that when you turn on the phone throught WI-FI it comes to a "screeching halt" and no action. for thought...=)

next code will be to work through WI-FI ... if you increase the connection time -

public static boolean isOnline() {
    boolean b = true;
    try{
        InetSocketAddress sa = new InetSocketAddress("SERVER_IP_ADDRESS", PORT);
        Socket ss = new Socket();
        ss.connect(sa, 1);            --> change from 1 to 500 (for example)
        ss.close();
    }catch(Exception e) {
        b = false;
    }
    return b;
}

Comments

2

First check if server is running and the server accepts the connection.

   public static boolean hostAvailabilityCheck()
{ 
    s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
    boolean available = true; 
    try {               
        if (s.isConnected())
        { s.close();    
        }               
        } 
    catch (UnknownHostException e) 
        { // unknown host 
        available = false;
        s = null;
        } 
    catch (IOException e) { // io exception, service probably not running 
        available = false;
        s = null;
        } 
    catch (NullPointerException e) {
        available = false;
        s=null;
    }


    return available;   
} 

8 Comments

The code on all three catch blocks is the same; it could be merged into one (and probably should be in this case).
It would be better to assume the server is NOT available (boolean available = false), and then set it to true if and only if you are able to reach it. That way, if there is an exception, or something glitches, we don't continue to connect based upon a now-incorrect boolean value.
@AaronDigulla I am not sure whether he is using J7
well you should deal this using thread to check connection. Since this is tcp you should use thread to send connection request and get the response often.
Testing s.isConnected() the line after you have just connected it is completely pointless. If it wasn't connected, the constructor would have thrown an exception.
|
-1

I used this method for my ServerUtil.

    public static boolean isOnline() {
    boolean b = true;
    try{
        InetSocketAddress sa = new InetSocketAddress("SERVER_IP_ADDRESS", PORT);
        Socket ss = new Socket();
        ss.connect(sa, 1);
        ss.close();
    }catch(Exception e) {
        b = false;
    }
    return b;
}

Comments

-1

I added max try count with 1 second delay:

public boolean checkServerStartedWithTries(String host, Integer port, int tries) {
  boolean isServerStarted = false;
  try {
    while(tries > 0) {
      if(isServerUp(restServerHost, port)) {
        LOG.info("Server has been started!");
        isServerStarted = true;
        return true;
      }
      LOG.info("Seems Server not started yet. Will sleep for one second");
      Thread.sleep(1000);
      tries --;
    }
  } 
  catch (Exception e) {
    return false;
  }
  return isServerStarted;
}

private boolean isServerUp(String host, int port) {
  try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress(host, port));
    LOG.info("Connected to Server successfully! Server is up.");
    return true;
  } 
  catch (IOException e) {
    return false;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.