Содержание
These samples are only valid for version 3. Please check the Samples directory for samples and documentation for version 4.0+
Preparation
This project also contains a managed MQTT client. The client has some additional functionality in comparison with the regular MqttClient. Those functionalities are reflecting the most common use cases and thus the ManagedClient provides a out-of-the-box MQTT client with the following features.
- The managed client is started once and will maintain the connection automatically including reconnecting etc.
- All MQTT application messages are added to an internal queue and processed once the server is available.
- All MQTT application messages can be stored to support sending them after a restart of the application
- All subscriptions are managed across server connections. There is no need to subscribe manually after the connection with the server is lost.
The managed Client is available as a separate nuget package (https://www.nuget.org/packages/MQTTnet.Extensions.ManagedClient/).
The following code shows how to setup and start a managed MQTT client.
// Setup and start a managed MQTT client.
var options = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithClientId("Client1")
.WithTcpServer("broker.hivemq.com")
.WithTls().Build())
.Build();
var mqttClient = new MqttFactory().CreateManagedMqttClient();
await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build());
await mqttClient.StartAsync(options);
// StartAsync returns immediately, as it starts a new thread using Task.Run,
// and so the calling thread needs to wait.
Console.ReadLine();
The managed client provides a UseConnectedHandler
method to attach a handler for when the client connects. There is also a ManagedMqttClient.ConnectingFailedHandler
property that can be set to track connection failures (in the 3.1.x release), and a ManagedMqttClient.ConnectingFailedAsync
event (in the 4.x release).
Message processing
Similar to the regular client the managed client also has a Publish method. But for the managed client this method will not throw an exception on failure because the message is only added to an internal queue and processed later.
But the managed client has several events which allows dealing with send errors etc.