使用 PAHO 订阅和读取 MQTT 消息
我正在使用 paho 发送和接收 mqtt 消息。到目前为止,发送消息没有问题,我使用mosquitto接收它们。
现在我想使用java客户端读取消息,我注意到关于接收消息的文档较少。
我实现了MqttCallback接口,但我仍然不知道如何阅读我订阅的主题的消息。
到目前为止,这是我的源代码,我可以使用mosquitto_sub来读取消息。
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class PahoDemo implements MqttCallback {
MqttClient client;
MqttClient subClient;
public PahoDemo() {
}
public static void main(String[] args) {
new PahoDemo().doDemo();
}
public void doDemo() {
try {
client = new MqttClient("tcp://192.168.118.11:1883", "Sending");
subClient = new MqttClient("tcp://192.168.118.11:1883",
"Subscribing");
client.connect();
subClient.connect();
subClient.subscribe("foo");
MqttMessage message = new MqttMessage();
message.setPayload("A single message from my computer fff"
.getBytes());
client.publish("foo", message);
client.disconnect();
client.close();
subClient.disconnect();
subClient.close();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void connectionLost(Throwable cause) {
// TODO Auto-generated method stub
}
@Override
public void messageArrived(String topic, MqttMessage message)
throws Exception {
System.out.println(message);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// TODO Auto-generated method stub
}
}