Skip to content
Takatoshi Kondo edited this page May 23, 2019 · 6 revisions

Offline Publish

When you set Clean Session = false, you can publish both before the first connection and after disconnection.

Here is the code example:

#include <iostream>
#include <mqtt_client_cpp.hpp>

int main() {
    boost::asio::io_context ioc;
    auto c = mqtt::make_sync_client(ioc, "test.mosquitto.org", 1883);

    c->set_client_id("cid1");
    c->set_clean_session(false);

    c->set_connack_handler(
        [&c](bool sp, std::uint8_t connack_return_code) {
            std::cout << "Connack handler called" << std::endl;
            std::cout << "Session Present: " << std::boolalpha << sp << std::endl;
            std::cout << "Connack Return Code: "
                      << mqtt::connect_return_code_to_str(connack_return_code) << std::endl;
            return true;
        }
    );
    c->set_close_handler(
        [] {
            std::cout << "closed" << std::endl;
        }
    );
    c->set_puback_handler(
        [&c](std::uint16_t packet_id) {
            std::cout << "puback" << std::endl;
            c->disconnect();
            return true;
        }
    );

    c->publish_at_least_once("mqtt_cpp_topic1", "test1");

    c->connect();

    ioc.run();
}

This code calls publish_at_least_once before the connection established.

In order to test the behavior, first, run Simple Subscriber, then run this program.

Simple Subscriber output:

Connack handler called
Session Present: false
Connack Return Code: accepted
suback received. packet_id: 2
subscribe success: exactly_once
publish received. dup: false pos: at_least_once retain: false
packet_id: 1
topic_name: mqtt_cpp_topic1
contents: test1

This program output:

Connack handler called
Session Present: true
Connack Return Code: accepted
puback
closed