0

我正在尝试使用下面的代码向 MQTT 发布和订阅数据,

try{
    ObjectMapper mapper = new ObjectMapper();
    MqttMessage message2 = new MqttMessage();
    MQTT mqtt_connect = new MQTT();
    mqtt_connect.setHost(Host_Address, Integer.parseInt(port));

    String topic = "/call/publishcall";
    mqtt_connect.setClientId("publishcall");
    mqtt_connect.setWillRetain(false);
    mqtt_connect.isWillRetain();
    mqtt_connect.setWillTopic(topic);                   
    BlockingConnection m_publisher = mqtt_connect.blockingConnection();

    m_publisher.connect();                   
    if(m_publisher.isConnected()){
        System.out.println("connected");                    
        message2.setPayload();

        Object o2 = message2;
        String s2 = o2.toString();
        mqtt_connect.setWillMessage(o2.toString());
        m_publisher.publish(topic, s2.getBytes(), QoS.AT_MOST_ONCE, false);

        Topic [] topics = {new Topic("/call/subscribecall", QoS.AT_MOST_ONCE)};                  
        m_publisher.subscribe(topics);                    
        Message message = m_publisher.receive(20000, TimeUnit.MILLISECONDS);
        byte[] payload = message.getPayload();
        String messageContent = new String(payload);
        System.out.println("Received message from topic: " + message.getTopic() + " Message content: " + messageContent);
        message.ack();
        if(messageContent =="0"){
            //i want to do something based on result 0
        }
        else if(messageContent =="1"){
                    //i want to do something based on result 1
        }
        else
        {
            //i want to do something based on result except 0 or 1
        }

        m_publisher.disconnect();
    }
    else
    {
        System.out.println("not connected");
    }

} catch (Exception e) {
    e.printStackTrace();
    return "failure";
}

但我可以将数据很好地发布到 MQTT。当他们发布主题名称为 /call/subscribecall 的数据时,我得到空指针异常,message.getPayload();但订阅者正确发送数据。

为什么我得到 null 而不是订阅者发送数据?订阅代码似乎没有获取数据。

我在哪里做错了?

4

0 回答 0