拉不拉稀肚拉稀 发表于 5 天前

使用C#连接MQTT 举行数据接收和数据处理,QoS1 持久会话模式 解决服务掉选

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、以下是程序接收到数据后的截图
https://img2024.cnblogs.com/blog/1394932/202502/1394932-20250224161536531-1491084436.png
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 使用C#连接MQTT 举行数据接收和数据处理,QoS1 持久会话模式 解决服务掉选