2017-08-28 363 views
0

我運行訂閱「Hello World」的簡單mqtt發佈者c代碼。無法訂閱mqtt中的多個主題

MQTT SUBSCRIBER1:

mosquitto_sub -h xx.xx.xx.xx -t "mq_test" 

。連續我運行相同的MQTT發佈者的代碼在另一個位置,並用不同的主題,以相同的主機訂閱。

MQTT subscriber2用戶:

mosquitto_sub -h xx.xx.xx.xx -t "mq_t" 

當我開始第二個發行計劃,第一MQTT訂閱停止。 爲什麼會出現這個問題,我認爲可以訂閱多個主題。

MQTT出版商的C代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <MQTTClient.h> 
#define ADDRESS  "tcp://xx.xx.xx.xx:abcd" 
#define CLIENTID "ExampleClientPub" 
#define TOPIC  "mq_test" //"mq_t" 
#define PAYLOAD  "Hello World!" 
#define QOS   1 
#define TIMEOUT  10000L 
int main(int argc, char* argv[]) 
{ 
    MQTTClient client; 
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; 
    int rc = 0; 
    MQTTClient_create(&client, ADDRESS, CLIENTID, 
     MQTTCLIENT_PERSISTENCE_NONE, NULL); 
    conn_opts.keepAliveInterval = 5; 
    conn_opts.cleansession = 1; 
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) 
    { 
     printf("Failed to connect, return code %d\n", rc); 
     exit(EXIT_FAILURE); 
    } 
    MQTTClient_message pubmsg = MQTTClient_message_initializer; 
    MQTTClient_deliveryToken token; 
    while(1){ 
     rc = 0; 
     pubmsg.payload = PAYLOAD; 
     pubmsg.payloadlen = strlen(PAYLOAD); 
     pubmsg.qos = QOS; 
     pubmsg.retained = 0; 
     MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token); 
     printf("Waiting for up to %d seconds for publication of %s\n" 
      "on topic %s for client with ClientID: %s\n", 
      (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID); 
     rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); 
     printf("Message with delivery token %d[%d] delivered\n", token,rc); 
    } 
    MQTTClient_disconnect(client, 10000); 
    MQTTClient_destroy(&client); 
    return rc; 
} 
+0

您可以添加訂閱代碼片段嗎? – Vardit

回答

1

您正在使用多個MQTT發佈者相同的代碼只有在這兩個出版商不斷變化的主題和客戶端ID保留通過給不同的客戶端ID爲same.please試用方案出版商。

+0

謝謝你的幫助。它解決了我的問題。 – student

0
#define CLIENTID "ExampleClientPub" 

每個應用程序/程序連接到MQTT代理需要自己獨特的clientId。
即「MyClnt001」,「MyClnt002」,「MyClnt003」等。

+0

這種方法解決了我的問題。謝謝 – student