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?

Josef
  • 2,648
  • 5
  • 37
  • 73
  • 1
    the static field `connected` seems to be pretty useless, because you never change it – Philipp Sander Jun 17 '13 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 – fge Jun 17 '13 at 12:27
  • This could help you http://stackoverflow.com/questions/9552743/proper-way-to-test-if-server-is-up-in-java Your URL(URL_TO_APPLICATION) could be SERVER_ADDRESS + TCP_SERVER_PORT also see this http://www.coderanch.com/t/205709/sockets/java/check-server – Yahya Arshad Jun 17 '13 at 12:27
  • What are you checking, the availability of the physical server, or an application running on it, like Tomcat? – raffian Jun 17 '13 at 14:14

4 Answers4

35

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 reliable ... if at all.)

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
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;
}
Viktor XXL
  • 61
  • 1
  • 2
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;   
} 
Murali
  • 774
  • 6
  • 12
  • 2
    The code on all three `catch` blocks is the same; it could be merged into one (and probably should be in this case). – Aaron Digulla Jun 17 '13 at 12:50
  • 7
    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. – Russell Uhl Jun 17 '13 at 12:50
  • @AaronDigulla I am not sure whether he is using J7 – Murali Jun 17 '13 at 12:52
  • but what if suddenly server is off? The main problem is how to again start with checking availability. Server applications is just waiting for connections and accepts data from clients. It doesn't send back any data to clients that can signal that server is going off. – Josef Jun 17 '13 at 13:00
  • 1
    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. – Murali Jun 17 '13 at 13:03
  • 3
    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. – user207421 Jun 18 '13 at 06:38
  • I'm still struggling with this problem and now i made this: boolean serverConnection = false; inside onCreate: new Thread(rConnection).start(); then: public Runnable rConnection = new Runnable() { @Override public void run() { while (serverConnection == false) { try { s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT); serverConnection = true; } catch (UnknownHostException e) { e.printStackTrace(); serverConnection = false; } catch (IOException e) { e.printStackTrace(); serverConnection = false; }}}}; – Josef Jun 18 '13 at 11:15
  • Also I have another thread for sending data to server constantly. If there is something wrong with server I get error inside catch block and in same time change servecConnection = false but thread rConnection doesen't register new state of variable. What I'm doing wrong? – Josef Jun 18 '13 at 11:15
-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;
}