MQTT客户端在没有订阅的情况下终止

时间:2017-02-18 18:26:53

标签: java mqtt subscribe

我已经设置了MQTT订阅,如下所示:

package com.mqttW.demo;
import java.text.SimpleDateFormat;
import java.util.*;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.*;

public class WSync implements MqttCallback {
    private String BROKER_URL = "";
    private String PROTOCOL = "tcp://";
    private String PORT = "1883";
    private String TOPIC_ROOT_UNCNF = "/P/uncnf/";
    private String TOPIC_ROOT_CNF = "/P/cnf/";

    private DbOperations dbo = new DbOperations();

    public void setBrokerUrl() {
        this.BROKER_URL = PROTOCOL + System.getenv("BROKER_DNS") + ":" + PORT;
    }

    public String getBrokerUrl() {
        return this.BROKER_URL;
    }

    public void publishPayload(String wName, String txnType, String payload) {
        String clientId = wName + "-PUB";
        String broker = this.getBrokerUrl();
        String topic = TOPIC_ROOT_UNCNF + txnType + "/" + wName;

        try {
            MqttClient w = new MqttClient(broker, clientId);
            w.connect();

            MqttMessage message = new MqttMessage(payload.getBytes());
            message.setQos(2);
            w.publish(topic, message);

            w.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void processTxns(String wName) {
        this.setBrokerUrl();

        String broker = this.getBrokerUrl();
        String clientId = wName + "-SUB";
        String topic = TOPIC_ROOT_CNF + wName + "/CR";
        MemoryPersistence persistence = new MemoryPersistence();   

        try {
            MqttConnectOptions c = new MqttConnectOptions();
            c.setCleanSession(false);

            MqttClient w = new MqttClient(broker, clientId, persistence);
            w.connect(c);
            w.setCallback(this);
            w.subscribe(topic, 2);
            System.out.println(w.getServerURI() + " " + w.getClientId() + " " + w.isConnected());

        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connectionLost(Throwable arg0) {
        System.out.println("Connection lost at : " + new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(new java.util.Date()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String s = new String(message.getPayload());
        System.out.println(s);
    }
}

使用此方法的类确实实现了MqttCallbackSystem.out.println正确显示代理URL,客户端ID和连接状态(true)。

所以,我没有得到的是,为什么代码会终止?为什么订阅没有设置为收听消息?

0 个答案:

没有答案