找回密码
 会员注册
查看: 143|回复: 0

ASP.NET MQTT 客户端通信

[复制链接]

250

主题

1

回帖

819

积分

管理员

积分
819
发表于 2024-2-29 08:37:08 | 显示全部楼层 |阅读模式
前期准备 本篇文章采用的Mqtt 2.8.5类库    Visual Studio2019 引用mqtt类库 对着新建的项目右键,管理Nuget程序包,搜索MQTTNet选择版本2.8.5点击安装 ![在这里插入图片描述](https://img-blog.csdnimg.cn/2020050514114361.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIzNTA2NjY=,size_16,color_FFFFFF,t_70) 了解MQTT常用事件以及属性 Connected     连接成功事件
Disconnected     断开连接事件
ApplicationMessageReceived    订阅事件
ClientId    客户端ID(唯一)
Topic    订阅主题(一个客户端可以订阅一个到多个主题,接收到的主题消息由订阅接收消息事件处理) 了解Qos 消息等级 mqtt消息等级称Qos分三个等级
MqttQualityOfServiceLevel.AtMostOnce    最多一次 MqttQualityOfServiceLevel.AtLeastOnce    最少一次 MqttQualityOfServiceLevel.ExactlyOnce    只有一次
注意:当qos=MqttQualityOfServiceLevel.AtLeastOnce或MqttQualityOfServiceLevel.ExactlyOnce的时候,就遇到问题了. 想让设备重新连接,获取到mqtt保存的消息,需要设置cleansession=false,就是设备每次登陆,都是用同一个session,而没有发出去的消息,是放在内存里面的,跟session关联,这里问题就大了.消息堆积,内存就挂了.所以有些 消息,需要自己业务逻辑处理或定期清理防止内存爆满

下面展示一些 内联代码片。

  1. // mqtt客户端
  2. private static MqttClient mqttClient;
  3. //ClientId,同SessionId性质一样,是客户端的身份识别唯一标识
  4. public string ClientId="";
  5. static void Main(string[] args)
  6. {
  7. Console.WriteLine("===启动客户端MQTT===");
  8. Console.Write("请输入ClientId:");
  9. ClientId = Console.ReadLine().ToLower().Trim();
  10. ConnectMqttService();
  11. while (true)
  12. {
  13. if (mqttClient == null)
  14. {
  15. ConnectMqttService();
  16. }
  17. }
  18. }
  19. public static void ConnectMqttService()
  20. {
  21. try
  22. {
  23. if (mqttClient == null || !mqttClient.IsConnected)
  24. {
  25. mqttClient = new MqttFactory().CreateMqttClient() as MqttClient;
  26. //连接成功
  27. mqttClient.Connected += MqttClient_Connected;
  28. //断开连接
  29. mqttClient.Disconnected += MqttClient_Disconnected;
  30. //订阅客户端或服务端发布的消息
  31. mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
  32. var options = new MqttClientOptions
  33. {
  34. ClientId = ClientId,
  35. CleanSession = true,
  36. ChannelOptions = new MqttClientTcpOptions
  37. {
  38. Server = "mqtt服务端ip地址",
  39. Port = Convert.ToInt32(端口号)
  40. }
  41. };
  42. Task.WaitAll(mqttClient.ConnectAsync(options));
  43. MqttSubscribe();
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. Console.WriteLine($"客户端ID标识为Client100001的消息连接MQTT服务器异常:" + ex.ToString());
  49. }
  50. }
  51. //MQTT发布消息 content消息内容
  52. public static void MqttClientPublish(String content)
  53. {
  54. var msg = new MqttApplicationMessage()
  55. {
  56. Topic = "$Topic" + ClientId,
  57. Payload = Encoding.UTF8.GetBytes(content),
  58. //QOS 消息等级
  59. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
  60. Retain = false
  61. };
  62. mqttClient.PublishAsync(msg);
  63. }
  64. //订阅MQTT消息
  65. public static void MqttSubscribe()
  66. {
  67. mqttClient.SubscribeAsync(new List<TopicFilter> {
  68. new TopicFilter("$Topic"+ClientId,MqttQualityOfServiceLevel.AtMostOnce)
  69. });
  70. }
  71. //订阅接收消息事件
  72. private static void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
  73. {
  74. //订阅内容
  75. String Payload = System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload);
  76. Console.WriteLine($"===订阅消息:{e.ClientId}内容:{Payload}===");
  77. }
  78. //mqtt断开连接两种形式 长时间订阅未接收到消息和服务端断开连接
  79. private static void MqttClient_Disconnected(object sender, MqttClientDisconnectedEventArgs e)
  80. {
  81. Console.WriteLine($"====已断开MQTT服务器,断开时间{DateTime.Now.ToString()}====");
  82. }
  83. private static void MqttClient_Connected(object sender, MqttClientConnectedEventArgs e)
  84. {
  85. Console.WriteLine($"=====连接MQTT服务器成功,连接时间{DateTime.Now.ToString()}====");
  86. }
复制代码

来源:https://blog.csdn.net/u012350666/article/details/105930517
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 11:19 , Processed in 0.373402 second(s), 26 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表