MqttClient从2个不同的班级

时间:2018-02-07 06:16:52

标签: java notifications mqtt paho

假设我有两个不同的项目。为简单起见,每个项目都包含一个java类。如何在java中使用MqttClient发布和订阅它们。这是我的代码,消息是发布但未被其他类接收。 Fist我创建了一个TopicPublisher类,它连接到Mqtt Broker并发送消息。然后我创建了一个TopicSubscriber类,它连接到同一个代理并订阅该主题。但即使Topic发布者正在发布消息但是另一个类没有给出任何输出。注意:这两个类在不同的项目中处于完全不同的文件夹中。我在这里做错了什么?这是我的代码:

public class TopicPublisher{
    public static void main(String[] args) {

    String topic        = "MQTT/Examples";
    String content      = "Message from MqttPublishSample";
    int qos             = 2;
    String broker       = "tcp://iot.eclipse.org:1883";
    String clientId     = "JavaSample";
    MemoryPersistence persistence = new MemoryPersistence();

    try {
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        System.out.println("Connecting to broker: "+broker);
        sampleClient.connect(connOpts);
        System.out.println("Connected");
        System.out.println("Publishing message: "+content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        System.out.println("Message published");
    } catch(MqttException me) {
        System.out.println("reason "+me.getReasonCode());
        System.out.println("msg "+me.getMessage());
        System.out.println("loc "+me.getLocalizedMessage());
        System.out.println("cause "+me.getCause());
        System.out.println("excep "+me);
        me.printStackTrace();
    }
}


public class TopicSubscriber implements MqttCallback{
public static void main( String[] args )
{
    try {
        MqttClient clientSub = new MqttClient("tcp://iot.eclipse.org:1883", "Subscribing");
        clientSub.connect();
        clientSub.subscribe("MQTT/#", 2);
    } catch (MqttException me) {
        // TODO Auto-generated catch block
        System.out.println("reason "+me.getReasonCode());
        System.out.println("msg "+me.getMessage());
        System.out.println("loc "+me.getLocalizedMessage());
        System.out.println("cause "+me.getCause());
        System.out.println("excep "+me);
        me.printStackTrace();
    }



}

@Override
public void connectionLost(Throwable arg0) {
    // TODO Auto-generated method stub
    System.out.println("1");
}

@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
    // TODO Auto-generated method stub
    System.out.println("2");
}

@Override
public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
    // TODO Auto-generated method stub
    System.out.println(arg1.getPayload()+"!!!!!!!");

}

}

1 个答案:

答案 0 :(得分:1)

您实现了MqttCallback但从未将其设置为回调到MqttClient。 一种解决方案是添加以下内容:

{{1}}

睡眠是必要的,因为否则应用程序会在回调执行之前退出。

另一种选择是使用带有IMqttMessageListener的subscribe作为参数。这样,您可以使用不同的处理程序订阅不同的主题。

可在此处找到一个很好的概述(德语):https://jaxenter.de/iot-allrounder-27208