随笔 - 16,  文章 - 0,  评论 - 0,  阅读 - 7324

1、准备工作

在开始写代码之前,我们先要准备下写程序的

  基础信息:MQTT地址、OrgID(机构ID)、API访问密钥

  连接模式:QoS1, 持久会话 ,防止服务掉选数据丢失问题,具体模式根据实际情况而定

2、我们先创建个C#的控制台应用程序,然后写入以下代码:

复制代码
// 创建MQTT客户端工厂
       var mqttFactory = new MqttFactory();
       var mqttClient = mqttFactory.CreateMqttClient();
 
       // 配置MQTT客户端选项
       var options = new MqttClientOptionsBuilder()
           .WithClientId("org-机构id-quickstart")  // 修改客户端ID
           .WithTcpServer("服务器地址", 1883) // 修改服务器地址,使用默认端口
           .WithCredentials("org-机构id", "秘钥") // 修改用户名
           .WithCleanSession(false)  // 添加这行,不清除会话
           .Build(); // 移除 TLS 配置,因为使用的是普通连接
 
       try
       {
           // 添加连接状态处理
           mqttClient.UseDisconnectedHandler(async e =>
           {
               Console.WriteLine("已断开连接!正在尝试重新连接...");
               await Task.Delay(TimeSpan.FromSeconds(5));
               try
               {
                   await mqttClient.ConnectAsync(options);
               }
               catch
               {
                   Console.WriteLine("重新连接失败");
               }
           });
 
           // 修改订阅主题以匹配您的格式
           string topic = "/device_sensor_data/机构id/+/+/+/+";
            
           // 添加订阅处理
           mqttClient.UseApplicationMessageReceivedHandler(e =>
           {
               string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
               string topic = e.ApplicationMessage.Topic ?? "";
                
               // 解析主题数据
               string[] topicParts = topic.Split('/');
               //将解析后的出具进行处理<br>
           });
 
           // 修改订阅配置
           var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
               .WithTopicFilter(topic, MqttQualityOfServiceLevel.AtLeastOnce)
               .Build();
 
           // 连接后进行订阅
           await mqttClient.ConnectAsync(options);
           await mqttClient.SubscribeAsync(subscribeOptions);
           Console.WriteLine("已成功连接并订阅主题 (QoS1, 持久会话)");
 
 
           // 保持程序运行
           Console.WriteLine("按任意键退出...");
           Console.ReadKey();
 
           // 断开连接
           await mqttClient.DisconnectAsync();
       }
       catch (Exception ex)
       {
           Console.WriteLine($"发生错误: {ex.Message}");
       }
复制代码

4、以下是程序接收到数据后的截图

 

posted on   水。  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示