How to read data from MQTT in Eclipse Paho?

℡╲_俬逩灬. 提交于 2019-12-25 06:45:20

问题


I am trying to read sensor data using MQTT, using Eclipse Paho. I am successfully connected, but I want to read data. my code so far:

  public static void main(String[] args) {
    MqttClient client;
    MqttMessage msg;
    MemoryPersistence persistence;
    MqttConnectOptions conn;
    IMqttMessageListener listen;

    String broker = "tcp://url:1883";
    String str = "password";
    char[] accessKey = str.toCharArray();
    String appEUI = "userID";


    try {
        persistence = new MemoryPersistence();
        client = new MqttClient(broker, appEUI, persistence);
        conn = new MqttConnectOptions();
        conn.setCleanSession(true);
        conn.setPassword(accessKey);
        conn.setUserName(appEUI);
        client.connect(conn);
        //client.connect();

        if(client.isConnected()) {
            System.out.println("Connected..");
        }else {
            System.out.println("Unable to connect");
            System.exit(0);
        }

        msg = new MqttMessage();
        byte[] data = msg.getPayload();
        System.out.println(d);



    }catch(Exception x) {
        x.printStackTrace();
    }

}

But i am unable to read data. Can someone please guide?


回答1:


You don't read data from a MQTT broker, instead you subscribe to a topic and get sent the data when ever a new message is published to that topic.

So you need to implement an instance of the MqttCallback interface and set it on the connection:

client.setCallback(new MqttCallback() {
    public void connectionLost(Throwable cause) {
    }

    public void messageArrived(String topic,
                MqttMessage message)
                throws Exception {
        System.out.println(message.toString());
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
    }
});

Then you need to tell the broker which topics you are interested in:

client.subscribe("topic/foo")


来源:https://stackoverflow.com/questions/38805669/how-to-read-data-from-mqtt-in-eclipse-paho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!