如何从Eclipse中的MQTT读取数据Paho? [英] How to read data from MQTT in Eclipse Paho?

查看:259
本文介绍了如何从Eclipse中的MQTT读取数据Paho?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Eclipse Paho,使用MQTT来读取传感器数据。我已成功连接,但我想要读取数据。
我的代码到目前为止:

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?

推荐答案

您不会从MQTT代理读取数据,您订阅一个主题并发送有一个新消息被发布到该主题的数据。

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

所以你需要实现一个 MqttCallback 接口并在连接上设置

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

client.setCallback(new MqttCallback() {
    pubic 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")

这篇关于如何从Eclipse中的MQTT读取数据Paho?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆