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>
相关推荐
leobertlan6 小时前
2025年终总结
前端·后端·程序员
面向Google编程7 小时前
从零学习Kafka:数据存储
后端·kafka
易安说AI8 小时前
Claude Opus 4.6 凌晨发布,我体验了一整晚,说说真实感受。
后端
易安说AI8 小时前
Ralph Loop 让Claude无止尽干活的牛马...
前端·后端
易安说AI8 小时前
用 Claude Code 远程分析生产日志,追踪 Claude Max 账户被封原因
后端
颜酱9 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
Coder_Boy_11 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
掘金者阿豪12 小时前
关系数据库迁移的“暗礁”:金仓数据库如何规避数据完整性与一致性风险
后端
ServBay13 小时前
一个下午,一台电脑,终结你 90% 的 Symfony 重复劳动
后端·php·symfony
sino爱学习13 小时前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端