1024programmer Asp.Net Lightweight communication protocol — MQTT

Lightweight communication protocol — MQTT

Lightweight communication protocol — MQTT

Introduction

1. Introduction to MQTT

MQTT (Message Queuing Telemetry Transport) is a lightweight message transport protocol commonly used for communication in the Internet of Things (IoT) and sensor networks. It is designed to transmit data over low-bandwidth, unstable, or high-latency network environments, making it ideal for communication between connected devices, especially in resource-constrained environments.

The main features of MQTT include the following:

  1. Lightweight: The MQTT protocol itself is very simple, and the message header occupies less bandwidth, making it efficient in low-bandwidth networks.

  2. Publish/subscribe model: MQTT uses a publish/subscribe model, in which the client can subscribe to a specific topic (Topic) and receive messages related to the topic. A publisher publishes a message to a specific topic, and all clients subscribed to that topic will receive the message.

  3. Reliability: MQTT supports three different levels of message transmission quality, including at most once, at least once and only once transmission. The appropriate level can be selected according to application requirements.

  4. Durable sessions: MQTT allows clients to establish persistent sessions so that previous subscription and messaging state can be restored when reconnecting after a connection is lost.

  5. QoS (Quality of Service): MQTT provides different QoS levels to ensure reliable delivery of messages. This includes QoS 0 (at most one transmission), QoS 1 (at least one transmission), and QoS 2 (only one transmission).

  6. Adaptability: MQTT can run on a variety of network protocols, including TCP/IP, WebSocket, and others.

In short, MQTT is a communication protocol that is very suitable for IoT and sensor networks and is widely used because of its lightweight and efficient characteristics. It allows devices to exchange information in real time, supporting a variety of applications including smart homes, industrial automation, agricultural monitoring, and more.

2. MQTT QoS mechanism

What is QoS mechanism? (https://www.emqx.com/zh/blog/introduction-to-mqtt-qos)

Many times, devices using the MQTT protocol run in network-limited environments, and relying only on the underlying TCP transmission protocol cannot fully guarantee the reliable arrival of messages. Therefore, MQTT provides a QoS mechanism, the core of which is to design a variety of message interaction mechanisms to provide different quality of services to meet users’ requirements for message reliability in various scenarios.

MQTT defines three QoS levels, which are:

  • QoS 0, delivered at most once.
  • QoS 1, delivered at least once.
  • QoS 2, delivered once.

Among them, using QoS 0 may cause message loss, using QoS 1 can ensure that messages are received, but messages may be repeated, and using QoS 2 can ensure that messages are neither lost nor repeated. The QoS level from low to high not only means an improvement in message reliability, but also an increase in transmission complexity.

MQTT .Net library — MQTTnet

MQTTnet is an open source, high-performance .NET library for MQTT-based communication. It provides an MQTT client and an MQTT server (broker) and supports the MQTT protocol until version 5. It is compatible with most supported .NET framework versions and CPU architectures.

Guthub address: https://github.com/dotnet/MQTTnet

MQTTnet is delivered via the NuGet package manager. The package can be found here: https://www.nuget.org/packages/MQTTnet/

In Visual Studio, manually install MQTTnet using the following command in the Package Manager console:

Install-Package MQTTnet
 

You can view the Demo source code directly on GitHub, or download the source code and open it with Visual Studio. It provides multiple Samples, and each Samples has different related information. Methods include the following categories:

  • Client_Connection_Samples —
  • Client_Publish_Samples
  • Client_Subscribe_Samples
  • Logger_Samples
  • Managed_Client_Simple_Samples
  • PackageInspection_Samples
  • RpcClient_Samples
  • Server_ASP_NET_Samples
  • Server_Diagnostics_Samples
  • Server_Intercepting_Samples
  • Server_Retained_Messages_Samples
  • Server_Simple_Samples
  • Server_TLS_Samples

You can download the source code and compile it, and after running it, it will be as follows:

image.png

Installation and use of MQTT message server under windows

Generally, common MQTT server software includes:

  • Mosquitto – A popular open source MQTT server, but it has no visual interface and requires the use of other tools to visualize it.

  • EMQX – A powerful open source MQTT server with a visual interface.

  • HiveMQ – HiveMQ is a commercial MQTT server that provides a free developer version.

It is recommended to use EMQX here, which providesst”, 1883)
.WithClientId(“Client1”)
.Build();
var connectResult = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

Console.WriteLine(“mqttClient connectResult: ” + connectResult.ResultCode.ToString());

while(true)
{
var msg = Console.ReadLine();

string topic = “testtopic/publish”;
string payload = $”{msg} {DateTime.Now:yyyy-MM-dd HH:mm:ss:fff}”; // Message content

var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(payload)
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // Set message quality
.WithRetainFlag(false) // Whether to retain the message
.Build();

await mqttClient.PublishAsync(message, CancellationToken.None);
}

}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

Next, write a subscription client code:

public static async Task CreateSubscribeMQTTClient()
 {
     try
     {
         MqttFactory mqttFactory = new MqttFactory();

         var mqttClient = mqttFactory.CreateMqttClient();

         var mqttClientOptions = new MqttClientOptionsBuilder()
             .WithTcpServer("localhost", 1883)
             .WithClientId("Client1")
             .Build();


         mqttClient.ApplicationMessageReceivedAsync += (e) =>
         {
             Task task = Task.Factory.StartNew(() =>
             {
                 var msgArray = e.ApplicationMessage.Payload;
                 string result = Encoding.UTF8.GetString(msgArray);
                 Console.WriteLine("Received: " + result);
             });

             return task;
         };

         var connectResult = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

         Console.WriteLine("mqttClient connectResult: " + connectResult.ResultCode.ToString());

         string topic = "testtopic/subscribe";

         var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
             .WithTopicFilter(topic)
             .Build();

         await mqttClient.SubscribeAsync(subscribeOptions);

     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }

 

Next, write the console Main method. Since the MQTT Client method is asynchronous, in order to avoid the console exiting, after calling the method, a While infinite loop is added to ensure that the console program is activated. Status, the code is as follows:

static void Main(string[] args)
 {
     Console.WriteLine("Choose a creation type: \r\n 1: PublishClient\r\n 2: SubscribeClient");
     var type = Console.ReadLine();
     switch (type)
     {
         case "1":
             _ = CreatePublishMQTTClient();
             break;
         case "2":
             _ = CreateSubscribeMQTTClient();
             break;

     }
     while (true) Thread.Sleep(1000);
 }

 

Three tests

First test the publishing client, select PublishClient in the console, and then wait for the connection. You can see that the connection result is Success. Send two test messages and you can see that MQTTX Desktop receives both.

image.png

Next, test the subscription client. Select SubscribeClient in the console, and then wait for the connection. You can see that the connection result is Success. Publish a message to the subscription client in MQTTX Desktop. You can see that the test is received in the console program. information.

image.png

Summary

In general, there is still relatively little information on using C# to write MQTT-related code, but fortunately the official documentation is detailed enough, and it still takes a lot of effort to try it out today. This article is intended to introduce some ideas and provide a brief understanding of MQTT, a lightweight communication protocol. It will be supplemented by a demo to deepen the understanding and become familiar with how to use it. There are also many reference articles at the end of the article for everyone to learn from.

Reference links

MQTTnet Guthub address: https://github.com/dotnet/MQTTnet

MQTT Getting Started Guide: https://www.emqx.com/zh/mqtt-guide

EMQX official documentation: https://www.emqx.io/docs/zh/v5.2/

EMQX command line documentation: https://www.emqx.io/docs/zh/v5.2/admin/cli.html

EMQX configuration manual: https://www.emqx.io/docs/zh/v5.2/configuration/configuration-manual.html

EMQX basic functions: https://juejin.cn/post/7081629128650129416

MQTTX client download: https://mqttx.app/zh/downloads

author:
Niuery Daily

Source:
https://www.cnblogs.com/pandefu/>

Email:
[email protected]

About the author: .Net Framework, .Net Core, WindowsForm, WPF, control library, multi-threading

The copyright of this article belongs to the author, and you are welcome to reprint it. However, this statement must be retained without the author’s consent, and it must be given in a prominent position on the article page.
Original link, otherwise we reserve the right to pursue legal liability.
If you have any questions, you can consult via email.

��

The copyright of this article belongs to the author, and you are welcome to reprint it. However, this statement must be retained without the author’s consent, and it must be given in a prominent position on the article page.
Original link, otherwise we reserve the right to pursue legal liability.
If you have any questions, you can consult via email.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/lightweight-communication-protocol-mqtt/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索