Skip to content
Takatoshi Kondo edited this page Feb 17, 2021 · 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_client(ioc, "test.mosquitto.org", 1883);

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

    c->set_connack_handler(
        [](bool sp, mqtt::connect_return_code connack_return_code){
            std::cout << "Connack handler called" << std::endl;
            std::cout << "Session Present: " << std::boolalpha << sp << std::endl;
            std::cout << "Connack Return Code: " << 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("mqtt_cpp_topic1", "test1", mqtt::qos::at_least_once);

    c->connect();

    ioc.run();
}

This code calls publish 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: 1
subscribe result: success_maximum_qos_2
publish received. dup: no qos: at_least_once retain: no
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