我正在尝试实现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