自学内容网 自学内容网

C#使用HslCommunication程序库快速创建MQTT客户端,实现连接、订阅主题、发送信息

说明: HslCommunication 这个通讯库是非常强大的,其稳定性非常可靠,虽然对于我个人来说在某些功能上配和项目还不算超级完美,但是够用 这个库可以在网上下载。

下面是MQTT客户端的完整的代码

using HslCommunication;
using HslCommunication.MQTT;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        void Main(string[] args)
        {
            try
            {
                string clientId = "AB";
                string ip = "192.168.0.118";
                int port = 1883;
                string Topic = "TTY";
                if (mqttClient != null) mqttClient.ConnectClose();

                Connect(ip, port, "admin", "123456");
                SubscribeMessage(Topic);
                PublishMessage(Topic, "Hello");
            }
            catch (Exception err)
            {
          
            }

            Console.ReadKey();

        }


        static MqttClient mqttClient;

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="clientId"></param>
        public void Connect(string ip, int port, string name , string pwd , string clientId = "ClientId")
        {
            try
            {
                if (mqttClient != null) mqttClient.ConnectClose();

                mqttClient = new MqttClient(new MqttConnectionOptions()
                {
                    ClientId = clientId,
                    IpAddress = ip,
                    Port = port,
                    Credentials = new MqttCredential(name, pwd),   // 设置了用户名和密码
                });

                OperateResult connect = mqttClient.ConnectServer();
                if (connect.IsSuccess)
                {
                    Console.WriteLine("连接Mqtt服务器成功");
                }
                else
                {
                    Console.WriteLine("连接Mqtt服务器失败");
                }
            }
            catch (Exception err)
            {
                Console.WriteLine($"连接Mqtt服务器失败[{err.Message}]");
            }


        }

        /// <summary>
        /// 发布信息
        /// </summary>
        /// <param name="topic"></param>
        public void PublishMessage(string topic, string Message)
        {
            try
            {
                mqttClient.PublishMessage(new MqttApplicationMessage()
                {
                    Topic = topic,                                                      // 主题
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,     // 消息等级
                    Payload = Encoding.UTF8.GetBytes(Message),        // 数据
                    Retain = false,                                                   // 是否保留
                });
            }
            catch (Exception err)
            {
                Console.WriteLine($"订阅失败[{err.Message}]");
            }
        }

        /// <summary>
        /// 订阅主题
        /// </summary>
        /// <param name="topic"></param>
        public  void SubscribeMessage(string Topic)
        {
            try
            {
                mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived; // 调用一次即可
                OperateResult Result = mqttClient.SubscribeMessage(Topic);     // 订阅A的主题
                if (Result.IsSuccess)
                {
                    Console.WriteLine($"订阅成功[{Topic}]");
                }
                else
                {
                    Console.WriteLine($"订阅失败[{Topic}]");
                }
            }
            catch (Exception err)
            {
                Console.WriteLine($"订阅失败[{err.Message}]");
            }
        }

        private static void MqttClient_OnMqttMessageReceived(MqttClient client, MqttApplicationMessage message)
        {
            Console.WriteLine($"收到服务器信息[{ message.ToString()}]");
        }
    }
}


原文地址:https://blog.csdn.net/weixin_50722786/article/details/142959464

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!