我使用MQTT和paho在android上接收和发布消息。
我的MQTT初始化有以下代码。
private void initializeMQTT(){
try{
mqttClient = new MqttClient(
"tcp://broker.hivemq.com:1883",
MqttClient.generateClientId(),
new MemoryPersistence()
);
mqttClient.connect();
mqttConnected = mqttClient.isConnected();
mqttClient.subscribe("testtopic/listen",1);
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) { //Called when the client lost the connection to the broker
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
mqttPayload = topic + ": " + Arrays.toString(message.getPayload());
mqttAnswer.setPayload(mqttPayload.getBytes());
mqttClient.publish("testtopic/publish",mqttAnswer);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {//Called when a outgoing publish is complete
messageInfoTest = "message was sent";
}
});
}
catch(MqttException e){
}
}
我只是想接收我收到的消息并将其作为测试发送回其他地方。
现在发生的事情是我第一次在testtopic / receive主题上发布时收到了。我似乎没有发布任何回复。如果我尝试向testtopic / receive发送另一条消息,则永远不会在我的android上接收。
任何人都知道我目前缺少什么?
谢谢!
答案 0 :(得分:0)
我刚遇到同样的问题,在调试PAHO后发现必须从调用messageArrived(...)回调的线程以外的其他线程调用client.publish。无法从messageArrived(...)回调代码中调用client.publish(...),因为它会导致死锁。