1. 介绍
MQTTnet 是一个强大的开源 MQTT 客户端库,适用于 C# 平台。它提供了丰富的功能和灵活的 API,可以轻松地构建基于 MQTT 协议的应用程序。本文将逐步学习如何使用 MQTTnet 库创建 MQTT 客户端,并实现基本的发布、订阅功能。
简介
什么是MQTT?
MQTT的发布和订阅架构
2. 搭建MQTT Broker
在Windows 系统上搭建 MQTT Broker,前一篇文章 Docker部署Eclipse Mosquitto开源MQTT的消息代理环境步骤(实践),我们使用docker搭建了Mosquitto环境。如果你觉得比较麻烦,也可以使用软件包来搭建环境。
具体的搭建步骤,可以查看官网。
3. 安装MQTTnet库
通过 NuGet 包管理器将 MQTTnet 库添加到我们的项目中。
4. 项目编码开发
1. MqttSubscriber项目
- 新建MqttSubscriber项目。
- 配置引用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项目。
- 配置引用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();
}
}
- 调试运行
5. 参考文档
- MQTT - The Standard for IoT Messaging
- Getting started
- 在.NET7中使用MQTTnet简单实现MQTT通信 - 翔星 - 博客园