0

Currently this is not supported in paho java library, 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?

CallanSM
  • 303
  • 2
  • 10
  • 20

1 Answers1

0

The best way would be implementing a callback (asynchronous event based) that informs you as soon as teh network is available again

interface INetworkCallback{

    void onNetworkStateChange(boolean newState);

}

and somewhere implement the interface

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    Well, network connection unavailable at first connect is just one possible case when something goes wrong. It can happened that broker is down when we try to connect. – CallanSM Mar 14 '17 at 15:07