订户处的MQTT同步消息接收

时间:2016-06-01 21:58:02

标签: c mqtt mosquitto subscriber

我有一个简单的发布者和用C编写的订阅者。我正在使用Paho MQTT库和mosquitto broker。我按照本网站的说明进行操作 - https://www.eclipse.org/paho/clients/c/(发布商代码与此链接相同)

第二个文件中的订阅者代码是 -

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"

#define ADDRESS     "tcp://localhost:7777"
#define CLIENTID    "CppClientSub"
#define TOPIC       "MQTT Examples"
#define PAYLOAD     "Hello World!"
#define QOS         2
#define TIMEOUT     10000L
volatile int count;
volatile MQTTClient_deliveryToken deliveredtoken;

void delivered(void *context, MQTTClient_deliveryToken dt) {
      printf("Message with token value %d delivery confirmed\n", dt);
          deliveredtoken = dt;
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) {   
      int i;
      char* payloadptr;
      count = count + 1;
      printf("Message arrived\n");
      printf("     topic: %s\n", topicName);
      //printf(" %d \n",count);

      payloadptr = (char*)message->payload;
      for(i=0; i<message->payloadlen; i++) {
          putchar(*payloadptr++);
      }
      putchar('\n');

      MQTTClient_freeMessage(&message);
      MQTTClient_free(topicName);
      return 1;
}

void connlost(void *context, char *cause) {
      printf("\nConnection lost\n");
      printf("     cause: %s\n", cause);
}

int main(int argc, char* argv[]) {
      count = 0;
      MQTTClient client;
      MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
      int rc;
      int ch;

      MQTTClient_create(&client, ADDRESS, CLIENTID,
             MQTTCLIENT_PERSISTENCE_NONE, NULL);
      conn_opts.keepAliveInterval = 60;
      conn_opts.cleansession = 0;

      MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

      if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
      {
          printf("Failed to connect, return code %d\n", rc);
          exit(-1);       
      }
      printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
                         "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
      MQTTClient_subscribe(client, TOPIC, QOS);

      do {
          ch = getchar();
      } while(ch!='Q' && ch != 'q');

      MQTTClient_disconnect(client, 10000);
      MQTTClient_destroy(&client);
      return rc;
}

mosquitto.conf文件 -

pid_file /var/run/mosquitto.pid
autosave_interval 100
persistence true
persistence_location /var/lib/mosquitto/
persistence_file mosquitto.db
connection_messages true
log_timestamp true
log_dest stderr
log_type error
log_type warning
log_type_debug
allow_anonymous false
protocol mqtt
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d

问题: - 我可以通过mosquitto代理运行发布者和订阅者代码。但是,订阅者在发布第二个消息时接收第一个消息,在发布第三个消息时接收第二个消息。当发布者程序停止时(通过关闭它正在运行的终端),在订户处接收最后发布的消息。我希望订阅者在代理获得消息后立即收到消息。我在发布者和订阅者中都有QoS = 2。

我哪里错了?它与经纪人设置有关吗?或者我设置发布者和订阅者的方式?

0 个答案:

没有答案