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++:

g++ SimpleMqttConsumer.cpp -lpaho-mqttpp3 -lpaho-mqtt3as -o simpleConsumer

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++:

g++ SimpleMqttProducer.cpp -lpaho-mqttpp3 -lpaho-mqtt3as -o simpleProducer

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.

./simpleConsumer

Start The Producer

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

./simpleProducer

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.

Time Left: 10
Time Left: 9
Time Left: 8
Time Left: 7
Time Left: 6
Time Left: 5
Time Left: 4
Time Left: 3
Time Left: 2
Time Left: 1
quit

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