Expand description
§rumqttc-v4-next
rumqttc-v4-next is the explicit MQTT 3.1.1 client crate in the rumqtt family.
Use it when you need MQTT 3.1.1 specifically. If you want the default MQTT 5 client, use rumqttc-next or rumqttc-v5-next instead.
This crate keeps the library target name as rumqttc so application code can stay familiar after migrating package names.
§Installation
cargo add rumqttc-v4-next§Examples
§A simple synchronous publish and subscribe
use rumqttc::{MqttOptions, Client, QoS};
use std::time::Duration;
use std::thread;
let mut mqttoptions = MqttOptions::new("rumqtt-sync", "test.mosquitto.org");
mqttoptions.set_keep_alive(5);
let (mut client, mut connection) = Client::builder(mqttoptions).capacity(10).build();
client.subscribe("hello/rumqtt", QoS::AtMostOnce).unwrap();
thread::spawn(move || for i in 0..10 {
client.publish("hello/rumqtt", QoS::AtLeastOnce, false, vec![i; i as usize]).unwrap();
thread::sleep(Duration::from_millis(100));
});
// Iterate to poll the eventloop for connection progress
for (i, notification) in connection.iter().enumerate() {
println!("Notification = {:?}", notification);
}§A simple asynchronous publish and subscribe
use rumqttc::{MqttOptions, AsyncClient, QoS};
use tokio::{task, time};
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let mut mqttoptions = MqttOptions::new("rumqtt-async", "test.mosquitto.org");
mqttoptions.set_keep_alive(5);
let (mut client, mut eventloop) = AsyncClient::builder(mqttoptions).capacity(10).build();
client.subscribe("hello/rumqtt", QoS::AtMostOnce).await.unwrap();
task::spawn(async move {
for i in 0..10 {
client.publish("hello/rumqtt", QoS::AtLeastOnce, false, vec![i; i as usize]).await.unwrap();
time::sleep(Duration::from_millis(100)).await;
}
});
while let Ok(notification) = eventloop.poll().await {
println!("Received = {:?}", notification);
}
}§Tracked protocol results
Tracked APIs return notices that resolve with MQTT protocol responses:
publish_tracked(...).wait_async() returns PublishResult,
subscribe_tracked(...).wait_async() returns SubAck, and
unsubscribe_tracked(...).wait_async() returns UnsubAck. Use
wait_completion_async() when only completion/failure status is needed.
See examples/tracked_notices.rs for a runnable async example.
Quick overview of features
- Eventloop orchestrates outgoing/incoming packets concurrently and handles the state
- Pings the broker when necessary and detects client side half open connections as well
- Throttling of outgoing packets (todo)
- Queue size based flow control on outgoing packets
- Automatic reconnections by just continuing the
eventloop.poll()/connection.iter()loop - Natural backpressure to client APIs during bad network
- Support for
WebSockets - Secure transport using TLS
- Unix domain sockets on Unix targets
- Strict MQTT 3.1.1 packet validation on the codec path
In short, everything necessary to maintain a robust connection
Since the eventloop is externally polled (with iter()/poll() in a loop)
out side the library and Eventloop is accessible, users can
- Distribute incoming messages based on topics
- Stop it when required
- Access internal state for use cases like graceful shutdown or to modify options before reconnection
§Important notes
-
Looping on
connection.iter()/eventloop.poll()is necessary to run the event loop and make progress. It yields incoming and outgoing activity notifications which allows customization as you see fit. -
Blocking inside the
connection.iter()/eventloop.poll()loop will block connection progress. -
Bounded clients apply backpressure through the client request channel. If the same task that drives
eventloop.poll()awaitspublish(),subscribe(),unsubscribe(),ack(), or another request-sending API while that bounded channel is full, it can self-block: the request is waiting for the event loop to read from the channel, but the event loop cannot make progress until that task polls it again. For bounded async clients, prefer drivingeventloop.poll()in a dedicated task and dispatch application work to other tasks. When dropping outgoing publishes under overload is intended, usetry_publish()and treat a full-channel error as the drop signal. -
Use
client.disconnect()/try_disconnect()for MQTT-level graceful shutdown. The event loop first flushes previously acceptedQoS0 publishes and drains previously acceptedQoS1/QoS2 publish and tracked subscribe/unsubscribe state (SUBACK/UNSUBACK), then sends terminal DISCONNECT. Usedisconnect_with_timeout()to bound this drain; if the timeout expires first, polling returnsConnectionError::DisconnectTimeoutand DISCONNECT is not sent. Usedisconnect_now()to send DISCONNECT immediately and abandon unresolved in-flight work. Dropping or aborting the transport closes locally without sending DISCONNECT and may trigger Will publication. -
Disconnect requests use the normal client request channel. If the event loop is not currently reading new requests because the outbound
QoS1/QoS2 publish inflight window is full or a packet-id collision is pending, a queueddisconnect_with_timeout()timeout starts only after the event loop observes the disconnect request, anddisconnect_now()is not an out-of-band transport abort. -
This crate is intentionally protocol-specific. It does not expose MQTT 5 features such as AUTH packets, topic aliases, or MQTT 5 property handling.
-
On Unix targets, local broker sockets are supported via
MqttOptions::new(..., Broker::unix(...)). When theurlfeature is enabled,MqttOptions::parse_url("unix:///tmp/mqtt.sock?client_id=...")is also supported.
§TLS Support
rumqttc supports two TLS backends:
use-rustls(default): Uses rustls withaws-lcas the crypto provider and native platform certificatesuse-native-tls: Uses the platform’s native TLS implementation (Secure Transport on macOS,SChannelon Windows, OpenSSL on Linux)
§TLS Feature Flags
| Feature | Description |
|---|---|
use-rustls | Enable rustls with aws-lc provider (recommended default) |
use-rustls-no-provider | Enable rustls without selecting a crypto provider |
use-rustls-aws-lc | Enable rustls with aws-lc provider |
use-rustls-ring | Enable rustls with ring provider |
use-native-tls | Enable native-tls backend |
use-rustls-aws-lc and use-rustls-ring are mutually exclusive. Enabling both results in a compile error.
§Important: Using Both TLS Features
When both use-rustls-no-provider and use-native-tls features are enabled:
- Configure TLS explicitly with
MqttOptions::set_transport(Transport::tls_with_config(...)) - Configure secure websockets explicitly with
Broker::websocket("ws://...")plusMqttOptions::set_transport(Transport::wss_with_config(...))
Secure websocket connections upgrade the TCP stream using the selected TlsConfiguration before the websocket handshake, so backend selection follows the provided TLS configuration.
In dual-backend dependency graphs, avoid relying on TlsConfiguration::default(), because default backend selection must be explicit.
Use TlsConfiguration::default_rustls() or TlsConfiguration::default_native() (when available) or pass an explicit configuration to
Transport::tls_with_config(...) / Transport::wss_with_config(...).
Native-tls WSS can use platform roots via TlsConfiguration::default_native() or a custom CA / identity via
TlsConfiguration::simple_native(...).
Re-exports§
pub use tokio_native_tls;use-native-tlspub use tokio_rustls;use-rustls-no-providerpub use mqttbytes::v4::*;pub use mqttbytes::*;
Modules§
- mqttbytes
- mqttbytes
Structs§
- Async
Client - An asynchronous client, communicates with MQTT
EventLoop. - Async
Client Builder - Builder for asynchronous MQTT clients.
- Broker
- Broker target used to construct
MqttOptions. - Client
- A synchronous client, communicates with MQTT
EventLoop. - Client
Builder - Builder for synchronous MQTT clients.
- Connection
- MQTT connection. Maintains all the necessary state
- Event
Loop - Eventloop with all the state of a connection
- Invalid
Topic - An error returned when a topic string fails validation against the MQTT specification.
- Iter
- Iterator which polls the
EventLoopfor connection progress - Mqtt
Options - Options to configure the behaviour of MQTT connection
- Mqtt
Options Builder - Builder for
MqttOptions. - Mqtt
State - State of the mqtt connection.
- Mqtt
State Builder - Builder for low-level MQTT 3.1.1 protocol state.
- Network
Options - Provides a way to configure low level network connection configurations
- Proxy
proxy - Publish
Notice - Wait handle returned by tracked publish APIs.
- Recv
Error - Error type returned by
Connection::recv - Subscribe
Notice - Wait handle returned by tracked subscribe APIs.
- Unsubscribe
Notice - Wait handle returned by tracked unsubscribe APIs.
- Validated
Topic - A newtype wrapper that guarantees its inner
Stringis a valid MQTT topic.
Enums§
- Client
Error - Client Error
- Connection
Error - Critical errors during eventloop polling
- Event
- Events which can be yielded by the event loop
- Manual
Ack - Prepared acknowledgement packet for manual acknowledgement mode.
- Notice
Failure Reason - Option
Error - Outgoing
- Current outgoing activity on the eventloop
- Proxy
Auth proxy - Proxy
Type proxy - Publish
Notice Error - Publish
Result - Publish
Topic - Topic argument accepted by publish APIs.
- Recv
Timeout Error - Error type returned by
Connection::recv_timeout - Request
- Requests by the client to mqtt event loop. Request are handled one by one.
- State
Error - Errors during state handling
- Subscribe
Notice Error - TlsConfiguration
use-rustls-no-provideroruse-native-tls - TLS configuration method
- TlsError
use-rustls-no-provideroruse-native-tls - Transport
- Transport methods. Defaults to TCP.
- TryRecv
Error - Error type returned by
Connection::try_recv - Unsubscribe
Notice Error
Functions§
- default_
socket_ connect - Default TCP socket connection logic used by the MQTT event loop.