如何在 Java 上使用 PAHO 订阅多个主题和多个 MqttCallback
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36425246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Subscribe Multiple topic and Multiple MqttCallback Using PAHO on Java
提问by tnchalise
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;
}
回答by jpwsutton
It looks like you're trying to create a new MQTT client for each subscription, this is likely very unnecessary for most applications. You might be better off just using one client and then subscribe using a topic array (As described here: subscribe(String[] topicFilters, int[] qos)) e.g.
看起来您正在尝试为每个订阅创建一个新的 MQTT 客户端,这对于大多数应用程序来说可能是非常不必要的。您最好只使用一个客户端,然后使用主题数组订阅(如此处所述:subscribe(String[] topicFilters, int[] qos))例如
mqttAsyncClient.subscribe(["/topic1", "/topic2", "/topic3"], [0,1,2]);
When any messages are delivered to your MqttCallback, then the topic that the message was published to will also be provided, so you'll still be able to tell where the message came from and be able to route it accordingly.
当任何消息传递到您的 MqttCallback 时,也会提供消息发布到的主题,因此您仍然可以判断消息来自何处并能够相应地路由它。
回答by tnchalise
MQTT allows you to subscribe any topic wildcardly. This means, you dont need to actully subscribe all topics.
"timentask/c/u000000000005", "timentask/c/u0000000GRP85"
Instead, subscribe to "timentask/c/#"
MQTT 允许您以通配符方式订阅任何主题。这意味着,您实际上不需要订阅所有主题。
"timentask/c/u000000000005", "timentask/c/u0000000GRP85"
相反,订阅"timentask/c/#"