Skip to main content

MQTT C++ Client for Posix and Windows

This C++ client provides an interface which is intended to mirror the Paho Java API as closely as possible. It requires the Paho MQTT C client library.

Features

Source

Source is available from the GitHub repository.

Download

Builds will be able to be downloaded here.

Building from source

Linux

The C++ client is built for Linux/Unix/Mac with CMake, and uses g++ or clang++ as the compiler. Because it requires a compliant C++11 compiler, only GCC 4.8.1 or clang 3.6 or later are supported. See the GitHub page for complete build instructions.

Windows

For Windows, CMake is used to generate a solution file for Visual Studio. Due to the C++11 requirement, the earliest version that can be used with the library is Visual Studio 2015. See the GitHub page for complete build instructions.

Documentation

Reference documentation is online.

Getting Started

These C++ clients connect to a broker using a TCP/IP connection using Posix or Windows networking, threading and memory allocation calls. They cannot be used with other networking APIs. For that, look at the Embdedded C/C++ client.

Here is a simple example of publishing with the C++ client synchronous API:

int main(int argc, char* argv[])
{
    const std::string TOPIC { "hello" };
    const std::string PAYLOAD1 { "Hello World!" };

    const char* PAYLOAD2 = "Hi there!";

    // Create a client

    mqtt::client cli(ADDRESS, CLIENT_ID);

    mqtt::connect_options connOpts;
    connOpts.set_keep_alive_interval(20);
    connOpts.set_clean_session(true);

    try {
        // Connect to the client

        cli.connect(connOpts);

        // Publish using a message pointer.

        auto msg = mqtt::make_message(TOPIC, PAYLOAD1);
        msg->set_qos(QOS);

        cli.publish(msg);

        // Now try with itemized publish.

        cli.publish(TOPIC, PAYLOAD2, strlen(PAYLOAD2), 0, false);

        // Disconnect

        cli.disconnect();
    }
    catch (const mqtt::exception& exc) {
        std::cerr << "Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << std::endl;
        return 1;
    }

    return 0;
}

Back to the top