qidao123.com技术社区-IT企服评测·应用市场

标题: 使用C#连接MQTT 举行数据接收和数据处理,QoS1 持久会话模式 解决服务掉选 [打印本页]

作者: 拉不拉稀肚拉稀    时间: 2025-2-24 15:30
标题: 使用C#连接MQTT 举行数据接收和数据处理,QoS1 持久会话模式 解决服务掉选
1、准备工作
在开始写代码之前,我们先要准备下写程序的
  基础信息:MQTT地址、OrgID(机构ID)、API访问密钥
  连接模式:QoS1, 持久会话 ,防止服务掉选数据丢失题目,具体模式根据现实情况而定
2、我们先创建个C#的控制台应用程序,然后写入以下代码:
  1. // 创建MQTT客户端工厂
  2.        var mqttFactory = new MqttFactory();
  3.        var mqttClient = mqttFactory.CreateMqttClient();
  4.        // 配置MQTT客户端选项
  5.        var options = new MqttClientOptionsBuilder()
  6.            .WithClientId("org-机构id-quickstart")  // 修改客户端ID
  7.            .WithTcpServer("服务器地址", 1883) // 修改服务器地址,使用默认端口
  8.            .WithCredentials("org-机构id", "秘钥") // 修改用户名
  9.            .WithCleanSession(false)  // 添加这行,不清除会话
  10.            .Build(); // 移除 TLS 配置,因为使用的是普通连接
  11.        try
  12.        {
  13.            // 添加连接状态处理
  14.            mqttClient.UseDisconnectedHandler(async e =>
  15.            {
  16.                Console.WriteLine("已断开连接!正在尝试重新连接...");
  17.                await Task.Delay(TimeSpan.FromSeconds(5));
  18.                try
  19.                {
  20.                    await mqttClient.ConnectAsync(options);
  21.                }
  22.                catch
  23.                {
  24.                    Console.WriteLine("重新连接失败");
  25.                }
  26.            });
  27.            // 修改订阅主题以匹配您的格式
  28.            string topic = "/device_sensor_data/机构id/+/+/+/+";
  29.             
  30.            // 添加订阅处理
  31.            mqttClient.UseApplicationMessageReceivedHandler(e =>
  32.            {
  33.                string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
  34.                string topic = e.ApplicationMessage.Topic ?? "";
  35.                
  36.                // 解析主题数据
  37.                string[] topicParts = topic.Split('/');
  38.                //将解析后的出具进行处理<br>
  39.            });
  40.            // 修改订阅配置
  41.            var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
  42.                .WithTopicFilter(topic, MqttQualityOfServiceLevel.AtLeastOnce)
  43.                .Build();
  44.            // 连接后进行订阅
  45.            await mqttClient.ConnectAsync(options);
  46.            await mqttClient.SubscribeAsync(subscribeOptions);
  47.            Console.WriteLine("已成功连接并订阅主题 (QoS1, 持久会话)");
  48.            // 保持程序运行
  49.            Console.WriteLine("按任意键退出...");
  50.            Console.ReadKey();
  51.            // 断开连接
  52.            await mqttClient.DisconnectAsync();
  53.        }
  54.        catch (Exception ex)
  55.        {
  56.            Console.WriteLine($"发生错误: {ex.Message}");
  57.        }
复制代码
4、以下是程序接收到数据后的截图

 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4