How To MQTT In CPP (C++)

A Data Consumer

The following program is an example of a simple data consumer built with the Paho Mosquitto C++ Library.

File: SimpleMqttConsumer.cpp

Compiling The Data Consumer

To compile the C++ source code into an executable file, use g++:

Make note of the library links -lpaho-mqttpp3 and -lpaho-mqtt3as. The library for the Mosquitto C++ interface is -lpaho-mqttpp3 which in turn requires the Mosquitto C interface-lpaho-mqtt3as as a dependency.

A Data Producer

The following program is an example of a simple data producer built with the Paho Mosquitto C++ Library.

File: SimpleMqttProducer.cpp

Compiling The Data Producer

To compile the C++ source code into an executable file, use g++:

Communicating Between The Clients

With each of the client programs compiled in to executables, they can now be used to communicate between one another.

Start The Consumer

I n one terminal, execute the simpleConsumer program to begin listening.

Start The Producer

With the Consumer started, open another terminal and execute the simpleProducer program to begin publishing.

The simpleProducer will begin publishing messages to a topic on the MQTT broker. These messages are picked up by the simpleConsumer and printed to the console.

The final message, quit, triggers the simpleConsumer to stop looping and return control to the console.