A lightweight, header-only MQTT v3.1.1 client library written in C++14, powered by Asio.
- Asynchronous API built on Asio
- Header-only design
- MQTT v3.1.1 protocol support
- CONNECT / CONNACK
- PUBLISH
- SUBSCRIBE / SUBACK
- UNSUBSCRIBE / UNSUBACK
- PINGREQ / PINGRESP
- DISCONNECT
- Built-in Keep-Alive mechanism with timeout detection
- Username/Password authentication support
- Variable-length encoding/decoding for Remaining Length
- Small, dependency-light footprint
- Pluggable logging - install a log callback to forward all library messages to your own logging backend (see Logging)
- mqtt_helper - High-level convenience wrapper with:
- Automatic connection & reconnection: unlimited or capped attempts, exponential or fixed backoff, re-armable after giving up
- Thread-safe io_context management
- Subscription persistence across reconnects
- Simple blocking-style API for easy integration
LiteMQTT/
├── CMakeLists.txt # Top-level build file
├── CHANGELOG.md # Notable changes, by release
├── 3rdparty/
│ └── asio/ # Vendored standalone Asio; CMakeLists.txt defines the `asio` target
├── cmake/
│ └── LiteMQTTConfig.cmake.in # Package config installed next to LiteMQTTTargets.cmake
├── examples/
│ ├── README.md # How to run the demo against a broker
│ └── demo.cc # Demo application (built as LiteMQTTDemo)
├── inc/
│ └── litemqtt/
│ ├── litemqtt.hpp # Umbrella header
│ ├── client.hpp # High-level mqtt_client API
│ ├── connection.hpp # TCP transport & framing
│ ├── packets.hpp # MQTT control packet structs
│ ├── packet_type.hpp # MQTT packet type enum
│ ├── buffer_writer.hpp
│ ├── buffer_reader.hpp
│ ├── error.hpp
│ ├── log.hpp # Log levels, callback interface & default sink
│ └── mqtt_helper.hpp # High-level helper with auto-reconnect
├── test/
│ ├── loopback_broker.hpp # Scripted MQTT peer shared by the socket tests
│ ├── codec_test.cc # GoogleTest unit tests
│ ├── client_test.cc
│ ├── qos_test.cc # QoS 1/2 handshakes, retransmission, give-up
│ ├── connection_test.cc # Framing, write serialization
│ ├── helper_test.cc # Lifetime, stop()/start(), backoff
│ └── log_test.cc
├── tools/
│ ├── reconnect_probe.cc # Reconnect / leak probe suite
│ └── reconnect_stress.cc # Publish-while-reconnecting stress harness
└── docs/
├── LiteMQTT设计文档.md
└── 测试补充清单.md # What the tests cover, and the gaps left
LiteMQTT is header only, so the build product is the interface target
LiteMQTT::litemqtt. It carries the include directory, C++14, the Windows
spellings Asio needs and Asio itself, so a consumer only writes
target_link_libraries(my_target PRIVATE LiteMQTT::litemqtt)Configure with CMake (e.g. with Ninja) and build:
cmake -B build -G Ninja
cmake --build buildThe build produces:
LiteMQTTDemo– the demo client (examples/demo.cc)reconnect_probe– reconnect / leak probe suite (tools/)reconnect_stress– publish-while-reconnecting stress harness (tools/)codec_test,client_test,qos_test,connection_test,helper_test,log_test– unit tests (if GoogleTest is available)
MSVC needs its environment loaded before CMake runs: without it the compiler is
found but rc.exe and mt.exe are not, and every link step fails. Configure from
a "x64 Native Tools Command Prompt" (or after calling vcvars64.bat), and let
CMake pick up ninja.exe from the PATH that the environment sets:
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
cmake -S . -B build_test -G Ninja -DCMAKE_BUILD_TYPE=Debug ^
-DLITEMQTT_REQUIRE_TESTS=ON -DLITEMQTT_FETCH_GTEST=ON
cmake --build build_test --parallel 4
ctest --test-dir build_test --output-on-failureLITEMQTT_FETCH_GTEST=ON matters here: Windows has no package manager that
ships GoogleTest, so without it the test targets are silently not created and
ctest reports "No tests were found". LITEMQTT_REQUIRE_TESTS=ON turns that
silent skip into a configure error. Both need network access the first time.
build_test/ is a separate tree from the Visual Studio generator output in
build/, which builds the demo and the tools but no tests. Both are ignored by
git.
Do not pass CMAKE_MAKE_PROGRAM by hand through cmd //c with a quoted path: not
all shells hand the quotes through intact, and a botched run leaves a
ninja.exe/ninja.exe/... cache entry that no build can use. Delete the build
directory and reconfigure if that already happened.
Everything is optional, and everything defaults to ON only when LiteMQTT is the
top-level project; dropped into another tree with add_subdirectory, it becomes
just the library plus a target the parent can link.
| Option | Default (top-level) | Effect |
|---|---|---|
LITEMQTT_BUILD_EXAMPLES |
ON | build the demo and the two tools |
LITEMQTT_BUILD_TESTS |
ON | build and register the unit tests |
LITEMQTT_INSTALL |
ON | generate install / find_package rules |
-DLITEMQTT_REQUIRE_TESTS=ON |
OFF | fail configure instead of quietly skipping the tests when GoogleTest is missing |
-DLITEMQTT_FETCH_GTEST=ON |
OFF | download googletest (v1.14, the last release that still supports C++14) when the system has none |
cmake --install build --prefix /some/prefixThat installs litemqtt/ under include/ together with the bundled Asio
headers, LiteMQTTTargets.cmake and LiteMQTTConfig.cmake under
lib/cmake/LiteMQTT, and lets a consumer do:
find_package(LiteMQTT 1.0 CONFIG REQUIRED)
target_link_libraries(my_target PRIVATE LiteMQTT::litemqtt)If the parent project already provides an asio target, that copy is used
instead of the bundled one and the build-interface include path is not exported.
The configuration CI uses:
cmake -B build -G Ninja -DLITEMQTT_REQUIRE_TESTS=ON -DLITEMQTT_FETCH_GTEST=ON
cmake --build build
ctest --test-dir build --output-on-failure --no-tests=error.github/workflows/ci.yml builds and exercises everything on three platforms:
| Runner | What runs |
|---|---|
ubuntu-24.04 (x86_64, gcc) |
unit tests, the full reconnect_probe suite, reconnect_stress (flap + weak link) |
windows-latest (x86_64, MSVC) |
unit tests, reconnect_probe, reconnect_stress (flap) |
ubuntu-24.04-arm (aarch64, gcc) |
unit tests, reconnect_probe |
The jobs build with /W3 (MSVC) or the default gcc warnings, and ctest is run
with --no-tests=error so a configuration that silently drops the tests fails
instead of passing.
The demo client connects to a local broker, subscribes to a topic and publishes a message every 10 ms until Ctrl-C:
./LiteMQTTDemo --host 127.0.0.1 --port 1883 \
--id litemqtt_demo \
--subscribe litemqtt/demo \
--publish litemqtt/demo \
--payload "Hello from LiteMQTT!"With authentication:
./LiteMQTTDemo --host 127.0.0.1 --port 1883 \
--username myuser --password mypass \
--subscribe litemqtt/demo \
--publish litemqtt/demo \
--payload "Hello from LiteMQTT!"The demo needs a broker of its own: it does not start one, and the publish loop runs at a fixed rate. Every option and what the program does with them is described in examples/README.md.
reconnect_probe exercises the failure modes that unit tests cannot observe: it
spins up a tiny broker on loopback, breaks the link in a specific way and prints
the numbers that decide pass/fail.
./reconnect_probe --help # list scenarios
./reconnect_probe framing # one scenario
./reconnect_probe all # everything, with a PASS/FAIL summary| Scenario | What it checks |
|---|---|
reconnect |
Broker drops the link repeatedly; the helper must come back. |
leak |
The helper must be destroyed after stop() and releasing it. |
leak_nostop |
Dropping the last owner without stop() must not leak the thread. |
stoplag |
stop() must not block while a long backoff timer is armed. |
restart |
start() after stop() must connect again. |
selfstop |
Calling stop() from the io thread (inside a callback) must be safe. |
badcreds |
A CONNECT rejected by the broker must close the session immediately. |
framing |
Many large writes plus broker-side QoS 1 pushes must stay in sync. |
backoff |
The io thread must stay responsive during the backoff wait. |
giveup |
A later start() must reset the attempt counter after giving up. |
rearm |
rearm_reconnect() resumes retrying after the limit was hit. |
fixed_delay |
set_reconnect_config(-1, 3000) retries forever, every 3 s. |
bigmsg |
Inbound PUBLISH with 1/2/3 byte remaining lengths parse correctly. |
bigpub |
Large publishes into a stalled peer must not corrupt the stream. |
Scenarios listen on 127.0.0.1 at 18840 + slot; export
LITEMQTT_PROBE_PORT_BASE to move the whole block. Exit code 0 means the
observed behaviour matched expectations.
reconnect_stress answers a different question than the probes: does anything
leak while the client keeps publishing through a link that is down, flapping or
half-dead? It starts a chaos broker on loopback, drives the link through a
scripted schedule and publishes QoS 1 messages at a fixed rate the whole time.
./reconnect_stress --help # list scenarios and options
./reconnect_stress --scenario flap --duration 30
./reconnect_stress --scenario weak --duration 120 --rate 200
./reconnect_stress --scenario soak --duration 300
./reconnect_stress --scenario mixed --duration 120| Scenario | Link behaviour |
|---|---|
flap |
The broker drops every session after ~80 ms, forever. |
long |
One long outage, then recovery. |
blackhole |
The listener accepts and then goes silent (no CONNACK, no reads). |
weak |
Slow reads plus short outages — a weak link, not a dead one. |
mixed |
All of the above in one schedule. |
soak |
Same schedule as mixed; use it for long endurance runs. |
The broker listens on 127.0.0.1 and asks the OS for a free port, so two runs
can never share traffic — the client is always pointed at its own broker. Pin
a port with --port N when you want to watch the wire (tcpdump) or reproduce
a specific setup. If the port cannot be bound the tool exits with status 2
instead of quietly measuring a listener owned by another process, and losing
the port in the middle of a run (an outage closes the listener, so a second
run can grab it) fails the run rather than reporting numbers from a broker
that never saw the traffic.
Give it at least ~30 s: weak and mixed start with a few seconds of weak but
working link, so a very short run can finish without ever reaching an outage —
and then fails the "link broke and came back" check on its own merits.
Every publish must be answered exactly once, and the summary checks that the
broker saw no framing or ordering errors, that the link really did break and
come back, that stop() returns immediately and that descriptors, threads and
RSS did not grow. The three resource counters are read from /proc, so they
are only meaningful on Linux (elsewhere those checks pass trivially). Run it
under AddressSanitizer for a leak check that goes beyond those counters (RSS is
meaningless there, so relax it):
g++ -std=c++14 -g -O1 -fsanitize=address -I inc -I 3rdparty/asio/include \
-pthread tools/reconnect_stress.cc -o reconnect_stress_asan
ASAN_OPTIONS=detect_leaks=1 ./reconnect_stress_asan --scenario mixed \
--duration 30 --rss-limit-mb 4096ASan on Linux does not cover everything, though: asio only checks a buffer's
validity when its iterator debugging is compiled in, which MSVC does for Debug
builds (and gcc does under _GLIBCXX_DEBUG, off by default). A buffer view into
a vector that has already been destroyed therefore surfaces as MSVC's
"can't dereference invalidated vector iterator" instead. Run the harness in a
Debug build too, which is what the Windows CI job does.
#include <asio.hpp>
#include <litemqtt/litemqtt.hpp>
int main() {
asio::io_context io;
auto client = std::make_shared<litemqtt::mqtt_client>(io);
client->set_client_id("my_client");
client->set_keep_alive(60);
client->set_clean_session(true);
client->set_username("myuser");
client->set_password("mypass");
client->on_connect([client](bool ok, uint8_t rc) {
if (ok) {
client->async_subscribe("hello/world");
client->async_publish("hello/world", "hi");
}
});
client->on_message([](std::string topic, std::string payload, uint8_t qos) {
// handle incoming message
});
client->async_connect("127.0.0.1", 1883, [](bool, uint8_t) {});
io.run();
}on_close() reports the end of a connect attempt that never got its CONNACK; the
loss of a session that was established comes through on_disconnected():
client->on_disconnected([...]() {
// the session that was up has been closed (peer gone, keepalive timeout, ...)
});The two are mutually exclusive, so on_connect(false, rc) plus on_disconnected()
covers every way a connection can end without reporting one failure twice.
#include <litemqtt/mqtt_helper.hpp>
int main() {
auto helper = std::make_shared<litemqtt::mqtt_helper>(
"127.0.0.1", 1883, "my_client");
helper->set_credentials("myuser", "mypass");
helper->set_keep_alive(60);
helper->set_reconnect_config(10, 1000); // max 10 attempts, 1s base delay
// helper->set_reconnect_config(-1, 3000); // or: retry forever, every 3 s
helper->on_message([](std::string topic, std::string payload,
uint8_t qos, uint16_t packet_id) {
// handle incoming message
});
helper->subscribe("hello/world", 1);
helper->start();
// Application runs independently, reconnection handled automatically
std::this_thread::sleep_for(std::chrono::seconds(300));
// With a finite max_attempts the helper eventually gives up (it logs a warn
// and is_reconnect_armed() turns false) but keeps running, so the session can
// be revived without tearing the io thread down:
if (!helper->is_reconnect_armed()) {
helper->rearm_reconnect(); // resets the counter, retries immediately
}
helper->stop();
}set_reconnect_config(max_attempts, base_delay_ms):
max_attempts |
Behaviour |
|---|---|
-1 |
Retry forever, always waiting base_delay_ms (no exponential growth). |
>= 0 |
Give up after that many consecutive failures; the delay grows as base_delay_ms * 2^attempt, capped at 30 s. A successful connect resets the counter. |
After giving up, is_reconnect_armed() returns false and rearm_reconnect()
puts the helper back to work (returns false if it is not running, in which case
start() is what you need). Both are safe to call from any thread.
Call client->async_unsubscribe(topic, callback) or
helper->unsubscribe(topic, callback). The optional callback has signature
void(bool success, std::string topic); success means the broker sent UNSUBACK,
not merely that the request was written. A failed write or a connection lost
while waiting for UNSUBACK reports failure. Client callbacks run on its io thread,
except that close() after the io loop stops fails pending requests on the
calling thread.
The helper immediately removes all exact matches of the topic filter from its
reconnect subscription list. For example, unsubscribing sensors/+ does not
remove a separate sensors/temperature subscription. While offline (including
before start() or after stop()), the helper still removes the local entries
and invokes the callback synchronously with false. It does not queue an
UNSUBSCRIBE for the next connection: with clean_session=false, the broker may
retain the old subscription, so retry while connected to remove it there.
The helper owns mqtt_client::on_connect and on_close for its reconnection
logic, so an application cannot install its own on the underlying client — and
those two callbacks report one failed attempt from more than one path. What it
needs instead is one edge per state change:
helper->on_connection([](litemqtt::connection_event event, uint8_t return_code) {
switch (event) {
case litemqtt::connection_event::connected:
// CONNACK accepted and the subscriptions replayed: publishing here is safe.
break;
case litemqtt::connection_event::disconnected:
// The session that was up has been closed.
break;
case litemqtt::connection_event::connect_failed:
// One attempt failed; return_code is the CONNACK code (4 = bad user name
// or password, 5 = not authorized), or 255 for a timeout / socket error.
break;
}
});| Event | When | return_code |
|---|---|---|
connected |
CONNACK accepted, after subscribes_ were replayed |
always 0 |
disconnected |
a connection that was established has been closed | always 0 |
connect_failed |
one connect attempt failed (CONNACK != 0, timeout, socket error) | the CONNACK code, or 255 |
A failed attempt reports connect_failed only — it never also reports
disconnected, which is what separates a link that just went away from one that
never came up. Nothing is reported after stop(). The callback runs on the io
thread and must not block there, though calling the helper's own methods from it
is fine.
connected_count() is a monotonic count of successful connects, not reset by
start(). Compare it in a periodic tick against the connected events you have
seen: if it is ahead, an event was missed and any state machine you drive from
these callbacks has to resynchronise.
Every attempt is bounded by a connect timeout that covers TCP connect and the CONNACK wait, so a blackholed peer cannot stall the session forever:
helper->set_connect_timeout(10000); // ms, default 10000; 0 disables the timeoutA timed-out attempt is treated like any other failure: on_connect(false, 255)
fires, the socket is closed and the reconnect policy decides what happens next.
Inbound packets are size-checked, because the remaining length comes from the peer and the body buffer is allocated at its full size before any payload arrives:
helper->set_max_packet_size(1024 * 1024); // bytes, default 1 MiB; 0 disablesA packet above the cap fails the read rather than being buffered. Raise it if the broker delivers large retained documents or images; setting it to 0 gives the peer control over how much the client allocates.
The outbound side has a matching guard. A broker that stops reading stalls the socket, and the frames waiting behind it accumulate with nothing draining them, so the queue is bounded:
helper->set_max_write_queue(1024); // frames, default 1024; 0 disablesOnce it is full a publish fails through its callback instead of being buffered. The bound counts frames rather than bytes, and applies to control packets as well as application messages.
That last point is a deliberate trade-off worth knowing about. One queue holds everything the client sends — publishes, PUBACK/PUBREC/PUBCOMP, PINGREQ, SUBSCRIBE, CONNECT, DISCONNECT — and a single limit covers it. The alternative, reserving headroom for control frames, would guarantee that a PINGREQ can always be sent, at the cost of a second limit to tune and a second path to get wrong.
The consequence: if the queue fills with large publishes while the broker is reading slowly, a PINGREQ waits behind them until the socket drains. 1024 frames is generous enough that this needs a genuinely extreme combination — a high publish rate against a peer that has nearly stopped reading — before keepalive starts to slip. If that ever shows up in practice, the fix is to reserve control frame slots rather than to raise the limit.
A frame refused this way is reported through the publish callback, so a publisher that honours its callbacks sees the backpressure rather than growing its own backlog.
While a session is not connected, publish() does not queue and does not touch
the socket — it reports callback(false, topic, qos, 0) immediately. That keeps
a publish from a timer from tearing down a connect attempt that is in progress;
re-publish from your on_connect(true) handler (or retry on the failure
callback) once the link is back.
The publish window lives in memory only — nothing is persisted — and the
callback contract is deliberately narrow. It is the same for mqtt_client and
mqtt_helper:
| QoS | callback(true, ...) means |
Retry inside the session |
|---|---|---|
| 0 | the PUBLISH frame was handed to the socket | none (fire and forget) |
| 1 | the broker's PUBACK for this packet id arrived | 5 s, up to 3 attempts, DUP = 1 on retries |
| 2 | the broker's PUBCOMP arrived (PUBLISH → PUBREC → PUBREL → PUBCOMP) | 5 s / 3 attempts for PUBLISH → PUBREC as above; 5 s / 3 attempts for PUBREL → PUBCOMP |
Three rules follow from that, and they are intentional:
- A disconnect fails everything still in flight.
notify_closed_once()reportscallback(false, topic, qos, packet_id)for every unacknowledged publish (and every un-SUBACKed subscribe) and drops it. Nothing is re-sent after the nexton_connect(true). - QoS 1 retries at most three times, then gives up. No PUBACK within 5 s
re-sends the frame with
DUP = 1; after the third attempt the publish is reported as failed even though the broker may in fact have received it. A QoS 2 message that never gets its PUBCOMP aborts the session instead (which, undermqtt_helper, meanson_connect(false, 255)and a reconnect). - There is no offline queue. Publishing while the session is down
(connecting, waiting for CONNACK, or between reconnects) reports
callback(false, topic, qos, 0)immediately — it is never buffered, and it does not disturb the connect attempt in progress. The in-flight window is bounded at 1000 publishes (kMaxPendingPublishes); when it is full the new publish is rejected withfalseand a warning is logged.
Republishing is the application's responsibility: re-send from
on_connect(true) whatever was in flight, or retry from the failure callback.
Keep that path idempotent — a DUP = 1 frame the broker did receive can still
be delivered twice. Subscriptions are per session as well, so re-issue them
after a reconnect; mqtt_helper does that for you for everything registered
before start().
If you need at-least-once across reconnects, keep the queue above the
library. tools/reconnect_stress.cc is a worked example of the bookkeeping:
it counts every publish and fails the run if one is never reported back (and
if any is reported twice).
The library never writes to std::cout / std::cerr directly any more: every
message goes through the sink installed with litemqtt::set_log_handler(), so it
can be forwarded to any logging backend (spdlog, glog, Qt, your own logger, ...).
#include <spdlog/spdlog.h>
#include <litemqtt/log.hpp>
litemqtt::set_log_handler([](const litemqtt::log_record& record) {
switch (record.level) {
case litemqtt::log_level::trace:
case litemqtt::log_level::debug: spdlog::debug("{}", record.message); break;
case litemqtt::log_level::info: spdlog::info("{}", record.message); break;
case litemqtt::log_level::warn: spdlog::warn("{}", record.message); break;
case litemqtt::log_level::error: spdlog::error("{}", record.message); break;
case litemqtt::log_level::off: break;
}
});
// Optional: discard everything below `info` (default threshold: log_level::trace).
litemqtt::set_log_level(litemqtt::log_level::info);If you only need level + message, use the adapter:
litemqtt::set_log_handler(litemqtt::make_log_handler(
[](litemqtt::log_level level, const std::string& message) {
my_logger::write(litemqtt::to_string(level), message);
}));Notes:
- The logger is process-wide; call
set_log_handler()once during startup (before creating clients is recommended, but it can be changed at any time). Pass a default-constructedlitemqtt::log_handler{}to restore the built-in sink (warn/error→std::cerr, the rest →std::cout). - The handler is invoked from the thread that emitted the event — usually the
Asio
io_contextthread — so it must be thread-safe. It is always called without the library holding any lock, so it may reconfigure the logger. Exceptions thrown by the handler are swallowed. litemqtt::log_recordcarrieslevel,file,lineandmessage(no trailing newline). Source location is captured by the internal macros.litemqtt::log_enabled(level)can be used to skip building expensive messages.
The process wide sink above is usually what you want when the whole application shares one logging backend. If you need to tag / route the records of individual connections differently (multiple brokers, per-tenant loggers, tests, ...), install a handler on the object instead — it wins over the global one:
// Per client (mqtt_client) ...
client->set_log_handler([id](const litemqtt::log_record& record) {
my_logger::write(id, record.level, record.message);
});
// ... or per helper (mqtt_helper): applies to the helper and to the mqtt_client
// it owns, so transport level records are routed to the same backend.
helper->set_log_handler([id](const litemqtt::log_record& record) { /* ... */ });
helper->set_log_handler(litemqtt::log_handler{}); // detach -> global sink againResolution order for every record:
- the handler of the emitting object (
mqtt_client/mqtt_helper), if installed; - otherwise the process wide handler from
litemqtt::set_log_handler(); - otherwise the built-in sink (
warn/error→std::cerr, rest →std::cout).
has_log_handler() / get_log_handler() let you query the installed sink;
set_log_handler() may be called at any time, from any thread, including while
the client is running. The severity threshold from litemqtt::set_log_level()
stays global and applies to per-instance handlers too. The same mechanism is
available for your own classes through litemqtt::detail::log_channel +
LITEMQTT_LOG_TO(channel, level) << ....
| Level | Where | Event |
|---|---|---|
| error | client.hpp |
TCP connect failure, protocol error (invalid PUBLISH QoS), invalid QoS passed to async_publish / async_subscribe, packet-id exhaustion |
| warn | client.hpp |
async_publish backpressure limit reached |
| error | mqtt_helper.hpp |
io_context exception, connection failure, null client, reconnect attempts exhausted |
| warn | mqtt_helper.hpp |
giving up after max reconnect attempts |
| info | mqtt_helper.hpp |
connection opened/closed, connected to broker, initiating/reconnecting |
| debug | mqtt_helper.hpp |
io_context thread exit, connection callback details |