你的上上个回答中onDeliveryComplete函数没有被调用,请重新给我示例代码
时间: 2023-06-27 18:08:19 浏览: 224
当然,以下是一个简单的示例代码:
```java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttSample {
public static void main(String[] args) throws MqttException {
String broker = "tcp://localhost:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
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");
String topic = "myTopic";
String message = "Hello World!";
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setQos(2);
System.out.println("Publishing message: " + message);
sampleClient.publish(topic, mqttMessage);
System.out.println("Message published");
sampleClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
System.out.println("Connection lost");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message arrived: " + message.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery complete");
}
});
sampleClient.subscribe(topic);
sampleClient.disconnect();
System.out.println("Disconnected");
}
}
```
在上面的代码中,我们使用了 Paho MQTT Java 客户端库来建立连接并发布消息。当消息成功发布后,我们设置了一个回调函数,以确保消息已传递到 MQTT 代理服务器上。在 `deliveryComplete()` 回调函数中,我们可以检查消息是否成功传递。如果未成功传递,我们可以根据需要采取适当的措施。
阅读全文