Background
I have been playing with MQTT for a project and encountered a odd issue. I am using paho as my MQTT client and VerneMQ as broker.
VerneMQ broker service is up and running, I can confirm this by runnnig netstat and I can see that 127.0.0.1:1883 entry is in LISTENING mode.
This is my code for client:
public class Producer implements MqttCallback {
private String brokerUri;
private String clientId;
public Producer(String brokerUri, String clientId){
this.brokerUri = brokerUri;
this.clientId = clientId;
}
public void doProduce(String topic, String payload){
MemoryPersistence memoryPersistence = new MemoryPersistence();
try {
MqttAsyncClient mqttAsyncClient = new MqttAsyncClient(brokerUri, clientId, memoryPersistence);
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
mqttAsyncClient.setCallback(this);
mqttAsyncClient.connect(mqttConnectOptions);
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(payload.getBytes());
mqttAsyncClient.publish(topic, mqttMessage);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void connectionLost(Throwable throwable) {
}
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("Message delivered!");
}
}
The following is my Main class
public class Main {
public static void main(String[] args) {
Producer producer = new Producer("tcp://127.0.0.1:1883", "producer1");
producer.doProduce("dummyTopic", "dummyMessage");
}
}
Issue
When I run my application, I see Client is not connected (32104) exception in the output.
If I change the line mqttAsyncClient.connect(mqttConnectOptions); to mqttAsyncClient.connect(mqttConnectOptions).waitForCompletion(); in Producer class, I can successfully connect to broker and I can see Message delivered! in the output.
If I am not mistaken waitForCompletion() will block the call until a response is received. And by adding this line I have effectively changed my AsyncClient connection to blocking connection, which is not the desired approach for me.
Question
How can I resolve this issue so paho MQTT client connects to broker in a non-blocking fashion? Have I missed something along the way?