Mosquitto C++ sample code to publish message

I start using mosquitto in a C++ program and I think documentation could be a little bit improved by some examples. To use mosquitto, there is a mosquittopp class acting as a wrapper on top of the mosquitto lib. Basically to create your own program you have to herit from that one and it is easy then.

Mosquitto lib can be managed as a thread or directly by calling the different sub function. In my point of view the thread approach is the better as otherwize you have to manage connection / disconnection manually. Mosquitto lib is then event managed, so you can subscribe to the callback event by surcharging the existing function.

Here is an exemple for a program just needing to publish messages to a broker.

class myMosq : public mosqpp::mosquittopp
{
private:
 const char     *     host;
 const char    *     id;
 const char    *     topic;
 int                port;
 int                keepalive;

 void on_connect(int rc);
 void on_disconnect(int rc);
 void on_publish(int mid);
public:
 myMosq(const char *id, const char * _topic, const char *host, int port);
 ~myMosq();
 bool send_message(const char * _message);
};

The initialization are done in the constructor as well as the thread creation :

myMosq::myMosq(const char * _id,const char * _topic, const char * _host, int _port) : mosquittopp(_id)
 {
 mosqpp::lib_init();        // Mandatory initialization for mosquitto library
 this->keepalive = 60;    // Basic configuration setup for myMosq class
 this->id = _id;
 this->port = _port;
 this->host = _host;
 this->topic = _topic;
 connect_async(host,     // non blocking connection to broker request
 port,
 keepalive);
 loop_start();            // Start thread managing connection / publish / subscribe
 };

The destructor, cleanly close what has been opened

myMosq::~myMosq() {
 loop_stop();            // Kill the thread
 mosqpp::lib_cleanup();    // Mosquitto library cleanup
 }

To send a message, we can simplely call the associated function

bool myMosq::send_message(const  char * _message)
 {
 // Send message - depending on QoS, mosquitto lib managed re-submission this the thread
 //
 // * NULL : Message Id (int *) this allow to latter get status of each message
 // * topic : topic to be used
 // * lenght of the message
 // * message
 // * qos (0,1,2)
 // * retain (boolean) - indicates if message is retained on broker or not
 // Should return MOSQ_ERR_SUCCESS
 int ret = publish(NULL,this->topic,strlen(_message),_message,1,false);
 return ( ret == MOSQ_ERR_SUCCESS );
 }

Then you can add some event handler

on_connect / on_disconnect are called by thread each time we exeperience a server connection / disconnection

void myMosq::on_disconnect(int rc) {
 std::cout << ">> myMosq - disconnection(" << rc << ")" << std::endl;
 }
void myMosq::on_connect(int rc)
 {
 if ( rc == 0 ) {
 std::cout << ">> myMosq - connected with server" << std::endl;
 } else {
 std::cout << ">> myMosq - Impossible to connect with server(" << rc << ")" << std::endl;
 }
 }

on_publish is called each time a message succeed to be sent to broker. The parameter is the message id you can set when publish.

void myMosq::on_publish(int mid)
 {
 std::cout << ">> myMosq - Message (" << mid << ") succeed to be published " << std::endl;
 }

22 thoughts on “Mosquitto C++ sample code to publish message

  1. the article is good, but i have a question, where did you find the libs and the .h files ?
    some detail codes are not clear for me for now, could you please send me your source code if convenient ?

      • Hi, i have visited the Mosquitto website but i have not found any example of a client in C++ with source code to run and use it. Could i download your example in any repository?
        Thanks in advance.

      • I assume you can copy past from the webpages.
        mosquitto source contains some good example also.

  2. I’m publishing messages in a server, so my goal is to publish as quickly as possible and return control to service clients. I don’t really want to spin up one or more threads to handle the publishing of messages, I was hoping there was an asynchronous way I could publish and not care about getting notifications, just immediately return.

  3. Hi Paul, thanks a lot for your post. Even if it has more than a year, I still found it very useful. However I’m having troubles with the connect_async method which always returns -1 to me, with the last mosquitto release 1.4.1. Have you by any chance experienced anything like that?

    • Actually I realized it just takes a lot of time (in the order of minutes) before establishing the connection, that’s why connect_async returns MOSQ_ERR_CONN_PENDING. Do you have any idea on the cause of this very long delay?

  4. Can you help me build an offline broker using c++ ? I want to create a system where I can send messages from one client to another, which are connected to my broker. Also, it would be great if you could give me a sample client for publishing a mesage(assembling the code given above)!!!

  5. Hi,

    The event handlers doesn’t work for me. Is there anything I have add to code to make them working?

    Thanks

    • The code below, doesn’t produce anything:
      myMosq *my_Mosq = new myMosq(“BlaBla”, “test”, “remotehost”, 1883);
      my_Mosq->send_message(“Hello world!”);

      No error, no messages to stdout from handlers, no mqtt message.

      • Hi, Julius, have you find a solution, samething here.. No errors no nothing only exiting program..
        Thanks..

  6. Hi, this post is very useful for me, but do you know how I can get the messages? I subscribe to the topic, but can’t get the messages from a topic.

  7. Hi,

    Anyone got an issue with the constructor during building project ?

    at constructor initialization:
    myMosq::myMosq(const char * _id,const char * _topic, const char * _host, int _port) : mosquittopp(_id)

    I have 2 errors :
    – Undefined reference to _imp___ZN6mosqpp11mosquittoppC2EPKcb
    – undefined reference to `vtable for myMosq

    Thanks in advance!

    Michel

  8. Hello,
    I understand this post is 4 years old but I need some information on publishing the message with QoS 1 or 2. Actually, I publish 1000 topics/8s for 20,000 times. When I do so, I observe the publisher’s message keeps growing. If I understand correctly the client app waits for publish ACK, but what the client App do once it receives the same.

    Should client App ask the broker to remove the message ID, if so how to do that? Thanks in advance.

    • Sounds like a good question for the Mosquito mailing list.
      Topic should free the message in the broker. Be careful with named subscription with persistance flag if you forget to clean the persistance when you stop using this subscription it will continue to grow. Messages are stored at the subscriptor level, not the publisher level.
      You can use $SYS stat topic to investigate potentially but this is a limitation of mosquito in my point of view : the low level of stats.

    • No, I don’t but google search should.
      The post is really old and currently I’m using Java clients for such application so the code would be really different.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.