eclipse-paho / eclipse-paho/paho.mqtt.java
Connecting for the first time - reconnect
- Dominant language
- Java
- Stars
- 2.3k
- Forks
- 919
- PR merge metrics
- No merged PRs in 30d
Description
- [ ] Bug exists Release Version 1.1.0 ( Master Branch)
- [ ] Bug exists in Snapshot Version 1.1.1-SNAPSHOT (Develop Branch)
According to James's comment over [here](https://github.com/eclipse/paho.mqtt.java/issues/9#issuecomment-197361273), 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?
Contributor guide
Assessment
This issue has not been assessed yet.