-
Notifications
You must be signed in to change notification settings - Fork 107
Offline Publish
Takatoshi Kondo edited this page Aug 28, 2019
·
6 revisions
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("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: 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
- Requirements
- Config
- Tutorial
- Authentication and Authorization
- Advanced topics
- Examples
- API Reference
- Versioning Policy
- How to contribute