eclipse / paho.mqtt.java

Eclipse Paho Java MQTT client library. Paho is an Eclipse IoT project.
https://eclipse.org/paho
Other
2.11k stars 882 forks source link

Connecting for the first time - reconnect #339

Open BojanSM opened 7 years ago

BojanSM commented 7 years ago

According to James's comment over here, this is not supported, but I need this functionality in our application. For example, on application startup, we didn't have network connection, but after 30 seconds or so, we established connection successfully so I want my client to connect automatically.

My question is - what would be best approach to accomplish this? What I tried so far is to try to reconnect if something goes wrong during connect method. And since we use RxJava I have scheduled execution of the same method which is responsible for client connection. It will be easier if I paste the code.

private void connect(String brokerUrl) {
    try {

        LOG.info("Connecting to the broker...");
        mqttClient.connect(connectionOptions, "Connecting", new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                LOG.info("Successfully conected to the broker.");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                LOG.error("Failed to connect to broker. Trying to reconnect in {} milliseconds...", connectionRetryTimeout, exception);
                // try to reconnect in few seconds
                Schedulers.io().scheduleDirect(() -> connect(brokerUrl), connectionRetryTimeout, TimeUnit.MILLISECONDS);
            }
        });

    } catch (MqttException e) {
        LOG.error("Connection error.", e);
    }
}

What happens like this is that, when network connection is available I manage to connect automatically, but second thread is created which continues to retry to connect to broker. Does anyone already implemented this, or do you have any other suggestions?

miketran78727 commented 7 years ago

I am not familiar with the scheduler package that you are using. Is it from this repository : https://github.com/ReactiveX/RxJava ? If you use standard Java Timer, https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html, you can cancel the timer in onSuccess() callback.

beersheba commented 6 years ago

@BojanSM I have the same problem. How did you resolved it for your app?

Andrei-Pozolotin commented 6 years ago

+1

nemecec commented 5 years ago

Exists also in 1.2.0