如何使用相同的BlockingConnection对象发布和订阅

时间:2015-12-23 05:45:11

标签: java publish-subscribe mqtt moquette

我正在尝试使用下面的代码

发布和订阅数据到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而不是订阅者发送数据?看来订阅代码没有得到数据。

我在哪里做错了?

0 个答案:

没有答案