c - MQTT synchronous message reception at the subscriber -
i have simple publisher , subscriber written in c. using paho mqtt libraries , mosquitto broker. followed instructions site - https://www.eclipse.org/paho/clients/c/ (the publisher code same in link)
the subscriber code in second file -
#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 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 connect, return code %d\n", rc); exit(-1); } printf("subscribing topic %s\nfor client %s using qos%d\n\n" "press q<enter> quit\n\n", topic, clientid, qos); mqttclient_subscribe(client, topic, qos); { ch = getchar(); } while(ch!='q' && ch != 'q'); mqttclient_disconnect(client, 10000); mqttclient_destroy(&client); return rc; }
mosquitto.conf file -
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
problem:- able run publisher , subscriber code through mosquitto broker. however, subscriber receives first message when second message published, second messaged received when third message published. when publisher program stopped (by closing terminal running in), last published message received @ subscriber. want subscriber receive message broker gets it. have qos = 2 in both publisher , subscriber.
where going wrong? got broker settings? or way have setup publisher , subscriber?