Simple implementation of MQTT communication using MQTTnet in .NET7
1. Introduction to MQTT
MQTT (Message Queuing Telemetry Transport) is a lightweight message transmission protocol, mainly used for communication between IoT devices. MQTT protocol adopts client/server architecture, supports publish/subscribe mode and point-to-point mode, and has the advantages of high efficiency, reliability and flexibility.
The MQTT protocol mainly consists of three elements: publisher, broker and subscriber. The publisher publishes the message to the proxy server, the subscriber subscribes the message from the proxy server, and the proxy server sends the message to the subscriber. Another important concept in the MQTT protocol is topic. Topics are used to define the type and content of messages. Publishers can publish messages to one or more topics, and subscribers can subscribe to messages from one or more topics. .
The MQTT protocol can transmit a large number of messages with low bandwidth over an unreliable network, and is suitable for various types of IoT applications, such as smart home, Internet of Vehicles, industrial Internet of Things, etc. Due to its light weight, high reliability, and fast response, the MQTT protocol has been widely used in the field of Internet of Things.
2. Introduction to MQTTnet
MQTTnet is a cross-platform, high-performance and open source MQTT client library and server implementation. It is one of the mainstream MQTT implementations on the .NET platform. Based on MQTTnet, users can easily integrate MQTT functions on the .NET platform to realize functions such as message transmission of the MQTT protocol.
Source address: https://github.com/dotnet/MQTTnet
3. UseMQTTnet**** in .NET7
1. Project preparation
First create two .NET7 console projects, which are used to simply implement the function of publishing message subscription. One project is the server and one client.
Then install the MQTTnet package. Here we choose to install version 3.12. The gap between MQTTnet versions is relatively large. You can install it in the Nuget package manager or use commands to install it.
dotnet add package MQTTnet --3.12
2. Server-side code writing
Write server-side code, the snippet code is as follows:
public static async Task MQTTP()
{
var factory = new MqttFactory();
var client = factory. CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithTcpServer("localhost", 1883)
.Build();
await client.ConnectAsync(options);
while (true)
{
Console.WriteLine("Enter the information to be published: ");
var message = Console. ReadLine();
var mqttMessage = new MqttApplicationMessageBuilder()
.WithTopic("testTopic")
.WithPayload(Encoding.UTF8.GetBytes(message))
.WithExactlyOnceQoS()
.Build();
await client.PublishAsync(mqttMessage);
}
}
//transfer
static async Task Main(string[] args)
{
#region test
await MQTTP();
#endregion
}
3. Client code writing
Write the following code on the client side:
public static async Task MQTTClientTest()
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithTcpServer("localhost", 1883)
. Build();
client.UseApplicationMessageReceivedHandler(e =>
{
Console.WriteLine($"Received message: {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
});
await client.ConnectAsync(options);
await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("testTopic").Build());
}
//transfer
static async Task Main(string[] args)
{
#region test
await MQTTClientTest();
#endregion
}
In this way, the function of publish and subscribe is simply completed. In this example, the publisher publishes the message to the “testTopic” topic, and the subscriber subscribes to the same topic. Once a new message arrives, it will be printed out. This is just a simple example. The actual use of MQTT is based on specific project scenarios, such as exception handling.
4. Conditions and methods of use:
First download and install MQTT on the official website: https://mqtt.org/.
Then change the port number of the project to the port configured by mqtt. You can try running two projects at the same time. You can try the code above.
Conclusion
This article introduces the simple use of MQTT in .NET7. MQTT has many functions, and you can use other functions according to the MQTTnet API. I hope this article can bring you something, welcome to leave a message and complain.
Source public account: DotNet development job hopping