Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client keeps on disconnecting and reconnecting #258

Closed
1 of 2 tasks
arpitkh96 opened this issue Sep 4, 2016 · 10 comments
Closed
1 of 2 tasks

Client keeps on disconnecting and reconnecting #258

arpitkh96 opened this issue Sep 4, 2016 · 10 comments

Comments

@arpitkh96
Copy link

arpitkh96 commented Sep 4, 2016

Please fill out the form below before submitting, thank you!

  • Bug exists Release Version 1.1.0 ( Master Branch)
  • Bug exists in Snapshot Version 1.1.1-SNAPSHOT (Develop Branch)

Here's the class

public class MessageReciever implements MqttCallbackExtended {

    Gson gson;
    static String subscribeTopic;
    static MessageReciever m = new MessageReciever();
    static MqttClient sampleClient;

    static void subscribe(String topic, String clientId) {
        int qos = 2;
        subscribeTopic = topic;
        try {
            if (sampleClient == null) {
                sampleClient = new MqttClient(broker, clientId, new MemoryPersistence());
            }

        System.out.println("Connecting");
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setAutomaticReconnect(true);
            sampleClient.setCallback(m);
            sampleClient.connect(connOpts);
        System.out.println("Connected");
        } catch (MqttException me) {
            me.printStackTrace();
        }
    }

    @Override
    public void connectionLost(Throwable thrwbl) {
        System.out.println("Connection lost ");

    }

    @Override
    public void messageArrived(String string, MqttMessage mm) throws Exception {
        System.out.println("Message " + mm.toString() + "\n" + string);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken imdt) {

    }

    @Override
    public void connectComplete(boolean bln, String string) {
        System.out.println("On Connection Complete");
        try {
            sampleClient.subscribe(subscribeTopic, 2);
        } catch (MqttException ex) {
            Logger.getLogger(MessageReciever.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Logs after calling subscribe() once

Connecting
On Connection Complete
Connected
Connection lost 
On Connection Complete
Connection lost 
On Connection Complete
Connection lost 
On Connection Complete
goes on and on..
@miketran78727
Copy link
Contributor

I cannot reproduce the problem.. Perhaps, you can explain the steps in more details.. I copied your code and changed it little bit as follows:

package autoconnect.test;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


public class MessageReceiver implements MqttCallbackExtended {

    String broker;
    String clientId;
    String subscribeTopic;
    MqttClient client = null;

    MessageReceiver(String broker, String clientId, String subscribeTopic) {
        this.broker = broker;
        this.clientId = clientId;
        this.subscribeTopic = subscribeTopic;
    }

    void subscribe() {

        try {
            if (client == null) {
                client = new MqttClient(broker, clientId, new MemoryPersistence());
            }

            System.out.println("Connecting");
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setKeepAliveInterval(10);
            connOpts.setCleanSession(true);
            connOpts.setAutomaticReconnect(true);
            client.setCallback(this);
            client.connect(connOpts);
            System.out.println("Connected");

        } catch (MqttException me) {
            me.printStackTrace();
        }
    }

    void quit() {
        final String METHOD = "quit";
        try {
            client.disconnect();
            System.out.println(METHOD + " disconnected!");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connectionLost(Throwable thrwbl) {
        System.out.println("Connection lost ");

    }

    @Override
    public void messageArrived(String string, MqttMessage mm) throws Exception {
        System.out.println("Message " + mm.toString() + "\n" + string);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken imdt) {

    }

    @Override
    public void connectComplete(boolean bReconnect, String host) {
        final String METHOD = "connectComplete";
        System.out.println(METHOD + " Connected to " + host + " Auto reconnect ? " + bReconnect);
        try {
            client.subscribe(subscribeTopic, 2);
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }
}

The test program:

package autoconnect.test;

public class test01 {

    public static void main(String[] args) {
        String broker = "tcp://messagesight.demos.ibm.com:1883";
        String clientId = "abc012345";
        String subscribeTopic = "/test1";

        System.out.println("START TEST");

        MessageReceiver m = new MessageReceiver(broker, clientId, subscribeTopic);

        m.subscribe();

        try {
            Thread.sleep(120000);
            m.quit();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("END TEST");
        System.exit(0);

    }

}

The console shows that auto-reconnect was triggered and worked as expected:

START TEST
Connecting
connectComplete Connected to tcp://messagesight.demos.ibm.com:1883 Auto reconnect ? false
Connected
Sep 05, 2016 1:38:22 AM org.eclipse.paho.client.mqttv3.internal.ClientState checkForActivity
SEVERE: abc012345: Timed out as no activity, keepAlive=10,000 lastOutboundActivity=1,473,035,892,885 lastInboundActivity=1,473,035,882,922 time=1,473,035,902,885 lastPing=1,473,035,892,885
Connection lost 
connectComplete Connected to tcp://messagesight.demos.ibm.com:1883 Auto reconnect ? true
quit disconnected!
END TEST

@arpitkh96
Copy link
Author

Yours worked.No idea why mine didn't.

@arpitkh96
Copy link
Author

it just appeared again in android too


public class MainActivity extends AppCompatActivity implements VolleyInterface{
    /*Removed Code*/
MqttClient client = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*Removed Code*/
        subscribe();
    }

    public void subscribe() {

        try {
            if (client == null) {
                client = new MqttClient(URL_API.mqtt_broker, Utils.getdeviceId(this), new MemoryPersistence());
            }

            System.out.println("Connecting");
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setKeepAliveInterval(10);
            connOpts.setCleanSession(true);
            connOpts.setAutomaticReconnect(true);
            client.setCallback(new MqttCallbackExtended() {
                @Override
                public void connectComplete(boolean bReconnect, String host) {
                    final String METHOD = "connectComplete";

                    System.out.println(METHOD + subscribeTopic+" Connected to " + host + " Auto reconnect ? " + bReconnect);
                    try {
                        client.subscribe(subscribeTopic, 0);
                    } catch (MqttException ex) {
                        ex.printStackTrace();
                    }
                }
                @Override
                public void connectionLost(Throwable thrwbl) {
                    System.out.println("Connection lost ");
                }


                @Override
                public void messageArrived(String string, MqttMessage mm) throws Exception {
                    System.out.println(mm.toString());
                    /*Removed Code*/

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
            client.connect(connOpts);
            System.out.println("Connected");

        } catch (MqttException me) {
            me.printStackTrace();
        }
    }

    void quit() {
        final String METHOD = "quit";
        try {
            client.disconnect();
            System.out.println(METHOD + " disconnected!");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        quit();
    }
}

logs


 I/System.out:Connecting
 I/System.out: connectComplete/status/arpitkh96 Connected to "url" Auto reconnect ? false
I/System.out: Connected
I/System.out: /*My MQTT message*/
I/System.out: Connection lost 
I/System.out: connectComplete/status/arpitkh96 Connected to"url" Auto reconnect ? true
I/System.out:/*My MQTT message*/

Goes on and on
PS - The message is a retained

@arpitkh96 arpitkh96 reopened this Sep 9, 2016
@miketran78727
Copy link
Contributor

Are you using the same clientId in any other threads/process?

@arpitkh96
Copy link
Author

arpitkh96 commented Sep 9, 2016

Well..I am using device ID of phone as client Id so that's not possible.. It's only one device.And I tried changing client I'd and even broker... None helps

@miketran78727
Copy link
Contributor

The publisher is not on the same device, correct?

@arpitkh96
Copy link
Author

arpitkh96 commented Sep 9, 2016

Yea it's different. Can I do something here to see broker stats or something?

@arpitkh96
Copy link
Author

arpitkh96 commented Sep 10, 2016

Nvm.Its fixed. It was because i was running some ui thread code in 'onMessageArrived' . Though that should have raised exception

@vyshakhkj
Copy link

I had a the issue of keeps on connecting and reconnecting on connection loss. I was doing like, if connectionLost() method in MqttCallback class is called I will call mqttClient.connect(). This will end in a loop. So instead of calling mqttClient.connect(), I called mqttClient.reconnect(); and the issue fixed.

@francescovgg
Copy link

Hi everyone,
I'm facing a similar problem of frequent connection loss.
I'm using the pahho-mqtt C library on a linux gateway connected via GMS to the Microsoft IoT HuB (working as a broker).

On certain gateways, there are frequent connectionLost() callbacks (every few minutes). Inside the connectionLost() I simply raise a flag which is then read by the main thread application in order to perform a new MQTT connection. After the MQTT connection is performed succesfully, the connectionLost() is immediately called again.

void onConnectionLost(void *context, char *cause) { gAppLog.PrintLog(LOG_DEBUG_WS, "MQTT Connection lost: %s ", cause); gCloudHdl.bMQTTConnected = false; }
the "cause" string returns (null). In the main thread there is something similar to

if(!gCloudHdl.bMQTTConnected) {MQTTAsync_create(...); MQTTAsync_setCallbacks(...); MQTTAsync_connect(...); }

Any suggestions? Many thanks in advance.
Francesco

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants