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>
相关推荐
x***381626 分钟前
springboot和springframework版本依赖关系
java·spring boot·后端
韩立学长1 小时前
基于Springboot课堂教学辅助系统08922bq1(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
盖世英雄酱581362 小时前
java深度调试技术【第六七八章:宽字节与多字节】
java·后端
望道同学3 小时前
PMP/信息系统项目管理师 9 张 思维导图【考试必备】
前端·后端·程序员
码事漫谈3 小时前
C++11到C++23语法糖万字详解
后端
码事漫谈3 小时前
别人的C#看着难受?可能是你不清楚这些语法糖
后端
+VX:Fegn08954 小时前
计算机毕业设计|基于springboot+vue的学校课程管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
上进小菜猪4 小时前
魔珐星云让AI拥有“身体“的具身智能开发平台实战评测
后端
f***24114 小时前
springboot系列--自动配置原理
java·spring boot·后端