简体   繁体   中英

MQTT with paho on android, only receiving first message

I'm using MQTT with paho to receive and publish messages on android.

I have the following code for my MQTT initialization.

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){

    }

}

I just want to take the message I receive and send it back somewhere else as a test.

What happens right now is I receive the first time I publish on the testtopic/receive topic. I do not seem to be publishing anything back. And if I try to send another message to testtopic/receive it is never receive on my android.

Anybody has an idea of what I'm currently missing?

Thanks!

I just had the same problem, after debugging PAHO found that client.publish must be called from other thread than the thread calling messageArrived(...) callback. client.publish(...) can't be called from messageArrived(...) callback code, because it causes deadlock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM