订阅示例
- mqtt client 订阅
c#
using MQTTnet;
using NLog;
using System.Text;
namespace DQ_MQTT_Test
{
internal class Program
{
public static async Task Handle_Received_Application_Message()
{
string id = "4369";
string num = "004-074";
/*
* This sample subscribes to a topic and processes the received message.
*/
ILogger logger = LogManager.GetCurrentClassLogger();
var mqttFactory = new MqttClientFactory();
using (var mqttClient = mqttFactory.CreateMqttClient())
{
// 添加默认的MQTT端口1883
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer("127.0.0.1", 1883)
.Build();
// 添加连接事件处理
mqttClient.ConnectedAsync += async e =>
{
Console.WriteLine($"### CONNECTED WITH BROKER ###");
Console.WriteLine($"Connected session item: {e.ConnectResult}");
};
mqttClient.DisconnectedAsync += async e =>
{
Console.WriteLine($"### DISCONNECTED FROM BROKER ###");
if (e.ClientWasConnected)
{
Console.WriteLine($"Client was connected: {e.ClientWasConnected}");
}
};
// Setup message handling before connecting so that queued messages
// are also handled properly. When there is no event handler attached all
// received messages get lost.
mqttClient.ApplicationMessageReceivedAsync += e =>
{
Console.WriteLine("Received application message.");
var msg = Encoding.GetEncoding("gb2312").GetString(e.ApplicationMessage.Payload);
//Console.WriteLine(msg);
logger.Info($"{num} msg:{msg}");
Console.WriteLine($"Topic: {e.ApplicationMessage.Topic}");
Console.WriteLine($"Payload: {msg}");
return Task.CompletedTask;
};
try
{
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
}
catch (Exception ex)
{
Console.WriteLine($"连接MQTT服务器失贿 {ex.Message}");
return;
}
// 检查连接状怿
if (mqttClient.IsConnected)
{
Console.WriteLine("MQTT client is connected.");
}
else
{
Console.WriteLine("MQTT client is NOT connected.");
return;
}
// 修复WithTopicFilter的使用方弿
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(f => f.WithTopic($"State/{id}/{num}"))
.Build();
try
{
var subscribeResult = await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
// 输出订阅结果
Console.WriteLine($"MQTT client subscribed to topic. Result: {subscribeResult.Items.FirstOrDefault()?.ResultCode}");
}
catch (Exception ex)
{
Console.WriteLine($"订阅主题失败: {ex.Message}");
return;
}
Console.WriteLine("MQTT client subscribed to topic.");
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
static async Task Main(string[] args)
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
await Handle_Received_Application_Message();
Console.ReadLine();
}
}
}
.csproj
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MQTTnet" Version="5.0.1.1416" />
<PackageReference Include="NLog.Extensions.Logging" Version="6.0.3" />
</ItemGroup>
<ItemGroup>
<None Update="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
NLog.config
json
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/logs/caxamqtt.${shortdate}.txt" />
<target name="logconsole" xsi:type="Console" />
<target archiveAboveSize="4096"/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logconsole" />
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>