Josef
Josef

Reputation: 2720

Detect if connection is failed - Java Android

How to check if server is online or offline, and if is offline start connecting until server is on. I have tried with this:

        connectBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new Thread(rConnection).start();

        }
    });

   public Runnable rConnection = new Runnable() {

    @Override
    public void run() { 
        boolean status = connect();         
        while (!status)
        {
            System.out.println("Connection Status: " + status);
            status = Connect();
        }
    }
 };

public boolean Connect() {

        boolean status = false;

        try {
            s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);

            System.out.println("Socket: " + s.toString());

            if (s.toString() != "")
            {
                status = true;
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            status = false;
            s=null;
        } catch (IOException e) {
            e.printStackTrace();
            status = false;
            s=null;
        } catch (NullPointerException e)
        {
            e.printStackTrace();
            status = false;
            s=null;
        }

        return status;
    }

If server is running before staring app it connects successfully but if server is off or disconnects after some time I don't get any error message and it won't start reconnecting again. How to solve this?

Upvotes: 0

Views: 1198

Answers (3)

user207421
user207421

Reputation: 311048

How to check if server is online or offline, and if is offline start connecting until server is on

Try to connect to it when you need to connect to it, and handle the failures that result. At present you seem to be trying to maintain an eternal connection, which is never going to work. The best way to detect whether a resource is available is to try to use it at the time that you need to use it. Anything is subject to numerous sources of error such as timing window problems, testing the wrong thing, testing the right thing at the wrong time, and at best to overuse of scarce resources. Rethink your requirement.

Upvotes: 0

PeterMmm
PeterMmm

Reputation: 24630

Basically you may split this:

s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);

into

s = new Socket();
s.connect(remoteAddr,timeout)

And then control if connect returns on timeout or on successfull connection.

Upvotes: 1

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16152

Look at this thread for a solution and keywords: How can I monitor the network connection status in Android? . Also, consider retrying requests on a new connection if the underlying connection is lost (or times out).

Upvotes: 0

Related Questions