如何使用Java上的PAHO订阅多个主题和多个MqttCallback

时间:2016-04-05 11:34:33

标签: java mqtt

static String[] meandgroup = new String[]{"timentask/c/u000000000005", "timentask/c/u0000000GRP85", "timentask/c/u000000GRP107", "timentask/c/u0000000GRP84", "timentask/c/u000000GRP100"};
    public static List<MqttClient> mqttConnect(Object topicId) {
        try {
            mqttClient = new ArrayList<MqttClient>();
            for (int i = 0; i < meandgroup.length; i++) {
                //if (mqttClient.get(i) == null || !mqttClient.get(i).isConnected()){
                if (!globalData.GlobalDataSetGet.MQTT_SERVER_HOST_NAME.equals("") && !globalData.GlobalDataSetGet.MQTT_SERVER_USER_NAME.equals("")) {
                    String topicName = meandgroup[i];
                    mqttClient.add(MqttMgr.subscriber(globalData.GlobalDataSetGet.MQTT_SERVER_HOST_NAME,
                            globalData.GlobalDataSetGet.MQTT_SERVER_PORT_NUMBER, globalData.GlobalDataSetGet.MQTT_SERVER_USER_NAME,
                            globalData.GlobalDataSetGet.MQTT_SERVER_USER_PASSWORD, Constants.MQTT_CONNECTION_KEEP_ALIVE_SECS, topicName, "client" + globalData.GlobalDataSetGet.getUserIdValue, new ChatPaneWrite()));
                }
            }
        } catch (MqttException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mqttClient;
    }

2 个答案:

答案 0 :(得分:7)

您似乎正在尝试为每个订阅创建一个新的MQTT客户端,这对于大多数应用程序来说可能是非常不必要的。您可能最好只使用一个客户端,然后使用主题数组进行订阅(如下所述: subscribe(String[] topicFilters, int[] qos)) e.g。

mqttAsyncClient.subscribe(["/topic1", "/topic2", "/topic3"], [0,1,2]);

当任何消息传递到您的MqttCallback时,也会提供消息发布到的主题,因此您仍然可以分辨消息的来源并能够相应地路由它。

答案 1 :(得分:5)

MQTT允许您以通配方式订阅任何主题。这意味着,您不需要动态订阅所有主题。 "timentask/c/u000000000005", "timentask/c/u0000000GRP85" 而是订阅"timentask/c/#"