1
votes

I'm new to mqtt. Getting started I tried publishing and subscribing topics to mosquitto broker. I was able to publish messages. But my subscriber is not listening to the topic, it will start and stop without waiting/polling for messages.

Here is the subscriber code,

public class MqttSubscriber implements MqttCallback {
private static final String TOPIC = "iot/endpoint";

public static void main(String[] args) {
    new MqttSubscriber().listen();
}

public  void listen() {
    MqttClient client = null;
    try {
        client = MqttClientGenerator.generateSubscriberClient();
        client.connect();
        System.out.println("Fetching messages...");
        client.subscribe(TOPIC);
        client.setCallback(this);
        client.disconnect();
      } catch (MqttException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
    }
}

public void connectionLost(Throwable t) {
    t.printStackTrace();
}

public void deliveryComplete(IMqttDeliveryToken arg0) {

}

public void messageArrived(String topic, MqttMessage message) throws Exception {
    System.out.println("Message received from broker...");
    System.out.println("Received Message: -- ");
    System.out.println(message.getPayload().toString());
}
}

MqttClientGenerator :

public class MqttClientGenerator {
private static final String BROKER_URI = "tcp://localhost:1883";
private static final String CLIENT_ID = "pub";
private static final String SUBSCRIBER_ID = "sub";


private MqttClientGenerator () {}

public static MqttClient generatePublisherClient() throws MqttException{
    //adding timestamp to make client name unique every time
    return new MqttClient(BROKER_URI, CLIENT_ID+new Date().getTime());
}

public static MqttClient generateSubscriberClient() throws MqttException{
    //adding timestamp to make client name unique every time
    return new MqttClient(BROKER_URI, SUBSCRIBER_ID+new Date().getTime());
}
}

what am i missing here?

1
Your code seems correct, but one thing seems strange, you are actually calling the disconnect method on your client, try deleting this lineAlexi Coard
Works like a charm :-). Disconnecting the client inside subscriber was stupid had to move out of the block as part of terminator.Srinath R
Glad to help ;) I've made this as an answer to make it clearerAlexi Coard

1 Answers

0
votes

Try deleting the line where you disconnect the client.