5

我正在尝试实现一个 JAVA 应用程序,目的是发布到特定的 MQTT 主题。消息应使用 QoS 2 传送(仅传送一次)。

但是我似乎忘记了我的实现中的任何内容(下面的 JUnit 实现的代码),因此尽管没有客户订阅我的主题,但消息似乎总是被传递。有谁知道我的错在这里?

我在 Ubuntu 12.04 上使用 mosquitto MQTT 代理,在 JAVA 端使用 Eclipse Paho。

MqttAsyncClient client = new MqttAsyncClient("tcp://localhost:1883", MqttClient.generateClientId(), new MemoryPersistence());

    try {
        client.connect().waitForCompletion();
    } 
    catch (MqttException e) {
        throw new RuntimeException("Failed to connect message-broker. Maybe it has to be started via typing \"sudo mosquitto\" in a new terminal window.");
    }

    client.setCallback(new MqttCallback() {
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            // No part of that test
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            throw new RuntimeException("Message with QoS 2 marked as delivered, but no client subscribed to topic.");
        }

        @Override
        public void connectionLost(Throwable cause) {
            // Not part of that test
        }
    });

    IMqttDeliveryToken token = client.publish("just/another/topic/where/nobody/is/listening", "Important message with QoS 2".getBytes(), 2, false, null, new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            throw new RuntimeException("Message with QoS 2 marked as delivered, but no client subscribed to topic.");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            // Expected behaviour
        }
    });

    token.waitForCompletion();

    assertEquals(true, token.isComplete()); 
    assertNotNull(token.getException());        // Should be not null due to unsuccessful delivery with QoS 2
4

0 回答 0