简体   繁体   English

如何在Eclipse Paho中从MQTT读取数据?

[英]How to read data from MQTT in Eclipse Paho?

I am trying to read sensor data using MQTT, using Eclipse Paho. 我正在尝试使用Eclipse Paho使用MQTT读取传感器数据。 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? 有人可以指导吗?

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. 您不是从MQTT代理读取数据,而是订阅一个主题,并在向该主题发布新消息时发送该数据。

So you need to implement an instance of the MqttCallback interface and set it on the connection: 因此,您需要实现MqttCallback接口的实例并在连接上进行设置:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM