MQTT.Net

订阅示例

  1. 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>
相关推荐
踏浪无痕14 分钟前
JobFlow调度的难题:超时、补偿与漏调
后端·面试·架构
Postkarte不想说话15 分钟前
ElasticSearch操作系统环境设置
后端
i听风逝夜16 分钟前
Gradle秒级打包部署SpringBoot项目,行云流水
后端
why技术44 分钟前
如果让我站在科技从业者的角度去回看 2025 年,让我选一个词出来形容它,我会选择“vibe coding”这个词。
前端·后端·程序员
喵个咪1 小时前
Go单协程事件调度器:游戏后端的无锁有序与响应时间掌控
后端·游戏开发
Kiyra1 小时前
八股篇(1):LocalThread、CAS和AQS
java·开发语言·spring boot·后端·中间件·性能优化·rocketmq
木风小助理1 小时前
在 Spring Boot 中实现 JSON 字段的蛇形命
spring boot·后端·json
William_cl1 小时前
【保姆级】ASP.NET Razor 视图引擎:@if/@foreach 核心语法拆解(附避坑指南 + 生活类比)
后端·asp.net·生活
pangtao20252 小时前
【瑞萨RA × Zephyr评测】看门狗
java·后端·spring
码界奇点2 小时前
基于Spring Cloud与Vue.js的微服务前后端分离系统设计与实现
vue.js·后端·spring cloud·微服务·毕业设计·源代码管理