千千梦丶琪 发表于 2024-10-22 14:49:58

在Net8.0中使用 MQTTnet 开源库实现 MQTT 应用程序开发(实践)

https://i-blog.csdnimg.cn/direct/9697870648d44c719ddd6ded8ed6e930.png
1. 先容

MQTTnet 是一个强大的开源 MQTT 客户端库,适用于 C# 平台。它提供了丰富的功能和灵活的 API,可以轻松地构建基于 MQTT 协议的应用程序。本文将逐步学习如何使用 MQTTnet 库创建 MQTT 客户端,并实现根本的发布、订阅功能。
简介
https://i-blog.csdnimg.cn/direct/998713862e3d44eb8a14bb5cba2eabe7.png
什么是MQTT?
https://i-blog.csdnimg.cn/direct/b351465f30c14b1ba5b1c4e3cd8b0816.png
MQTT的发布和订阅架构
https://i-blog.csdnimg.cn/direct/ca545f90e0ce4167a74fe37e250b00a3.png
2. 搭建MQTT Broker

在Windows 系统上搭建 MQTT Broker,前一篇文章 Docker部署Eclipse Mosquitto开源MQTT的消息署理情况步调(实践),我们使用docker搭建了Mosquitto情况。如果你以为比较麻烦,也可以使用软件包来搭建情况。
https://i-blog.csdnimg.cn/direct/db9f15a24407442b8ea13357947e603a.png
详细的搭建步调,可以查看官网。
3. 安装MQTTnet库

https://i-blog.csdnimg.cn/direct/8fccf5e25b394525b6e3f200670528de.png
通过 NuGet 包管理器将 MQTTnet 库添加到我们的项目中。
https://i-blog.csdnimg.cn/direct/504daabb88df444185e4f8d14905df15.png
4. 项目编码开发

1. MqttSubscriber项目


[*]新建MqttSubscriber项目。
https://i-blog.csdnimg.cn/direct/f3b010882e964d7cb822c593de7ed927.png
[*]配置引用MQTTnet库
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
</PropertyGroup>
        <ItemGroup>
                <PackageReference Include="MQTTnet" Version="4.3.3.952" />
                <PackageReference Include="MQTTnet.Extensions.ManagedClient" Version="4.3.3.952" />
        </ItemGroup>

</Project>

[*]编写订阅代码
using System.Text;
using MQTTnet;
using MQTTnet.Client;

class Program
{
    static async Task Main(string[] args)
    {
      var options = new MqttClientOptionsBuilder()
            .WithTcpServer("localhost", 1883)
            .WithCredentials("root","root")
            .Build();

      var factory = new MqttFactory();
      var mqttClient = factory.CreateMqttClient();

      mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;

      await mqttClient.ConnectAsync(options);
      await mqttClient.SubscribeAsync("testtopic");

      Console.WriteLine("Press any key to exit.");
      Console.ReadKey();

      await mqttClient.DisconnectAsync();
    }

    private static Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
    {
      Console.WriteLine($"Received message: {Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment)}");
      return Task.CompletedTask;
    }
}
2. MqttPublisher项目


[*]新建MqttPublisher项目。
https://i-blog.csdnimg.cn/direct/b2573275cf29422f97fe345b2a11f852.png
[*]配置引用MQTTnet库
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
</PropertyGroup>
        <ItemGroup>
                <PackageReference Include="MQTTnet" Version="4.3.3.952" />
                <PackageReference Include="MQTTnet.Extensions.ManagedClient" Version="4.3.3.952" />
        </ItemGroup>

</Project>

[*]编写发布代码
using System;
using System.Text;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;

class Program
{
    static async Task Main(string[] args)
    {
      var options = new MqttClientOptionsBuilder()
            .WithTcpServer("localhost", 1883)
            .WithCredentials("root", "root")
            .Build();

      var factory = new MqttFactory();
      var mqttClient = factory.CreateMqttClient();

      var managedMqttClient = new MqttFactory().CreateManagedMqttClient();
      await managedMqttClient.SubscribeAsync("testtopic");

      await mqttClient.ConnectAsync(options);
      bool bcontinue = true;
      while (bcontinue)
      {
            string input = $"{DateTime.Now.ToString("HH:mm:ss fff")}:{Guid.NewGuid().ToString()}";         
            Console.WriteLine(input);
            var message = new MqttApplicationMessageBuilder()
                .WithTopic("testtopic")
                .WithPayload(Encoding.UTF8.GetBytes(input))
                .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce)
                .WithRetainFlag()
                .Build();

            await mqttClient.PublishAsync(message);
      }

      await managedMqttClient.StopAsync();
    }
}

[*]调试运行
https://i-blog.csdnimg.cn/direct/e470d0804b634483820e22358c729d73.png
5. 参考文档



[*]MQTT - The Standard for IoT Messaging
[*]Getting started
[*]在.NET7中使用MQTTnet简单实现MQTT通讯 - 翔星 - 博客园

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 在Net8.0中使用 MQTTnet 开源库实现 MQTT 应用程序开发(实践)