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>
相关推荐
用户848508146904 分钟前
SurrealDB 快速上手教程
数据库·后端
用户61474934277427 分钟前
JeecgBoot 项目理解与使用心得
后端
ZIQ1 小时前
单机线程池任务防丢设计与实现思路
后端
MaxHua1 小时前
我用 Java 飞算 AI 快速开发了一个音频转文字工具
后端
欧阳码农1 小时前
langgraph开发Deep Research智能体-项目搭建
前端·后端·langchain
BigYe程普1 小时前
出海技术栈集成教程(二):Supabase 登录与数据库配置
前端·后端·全栈
臻实1 小时前
Win10系统Ruby+Devkit3.4.5-1安装
开发语言·后端·ruby
汪子熙1 小时前
使用 Python 解析 X.509 格式的公钥证书
后端
陈明勇1 小时前
Go 1.25 重磅发布:性能飞跃、工具升级与新一代 GC 来袭
后端·go
用户6757049885021 小时前
Cookie、Session、Token、JWT 是什么?万字图解带你一次搞懂!看完这篇,你连老奶奶都能教
后端