服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#实现MQTT服务端与客户端通讯功能

C#实现MQTT服务端与客户端通讯功能

2022-12-22 14:36痕迹g C#

这篇文章介绍了C#实现MQTT服务端与客户端通讯的功能,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

关于MQTT

MQTT(消息队列遥测传输)是ISO 标准(ISO/IEC PRF 20922)下基于发布/订阅范式的消息协议。它工作在 TCP/IP协议族上,是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅型消息协议,为此,它需要一个消息中间件 。

MQTT是一个基于客户端-服务器的消息发布/订阅传输协议。MQTT协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联网(IoT)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

百度百科

MQTT示例

注: 该示例演示统一使用WPF, 简单MVVM模式演示, 复制代码需注意引用 NuGet包 GalaSoft

MQTT服务端建立:

演示界面:

C#实现MQTT服务端与客户端通讯功能

演示代码:

public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ClientInsTances = new ObservableCollection<ClientInstance>();
        }

        IMqttServer mqttServer;  //MQTT服务端实例

        string message; 

        /// <summary>
        /// 消息   用于界面显示
        /// </summary>
        public string Message
        {
            get { return message; }
            set { message = value; RaisePropertyChanged(); }
        }


        ObservableCollection<ClientInstance> clientInstances; //客户端登陆缓存信息

        /// <summary>
        /// 客户端实例
        /// </summary>
        public ObservableCollection<ClientInstance> ClientInsTances
        {
            get { return clientInstances; }
            set { clientInstances = value; RaisePropertyChanged(); }
        }
     //开启MQTT服务
        public void OpenMqttServer()
        {
            mqttServer = new MqttFactory().CreateMqttServer();
            var options = new MqttServerOptions();

            //拦截登录
            options.ConnectionValidator = c =>
            {
                try
                {
                    Message += string.Format("用户尝试登录:用户ID:{0}	用户信息:{1}	用户密码:{2}", c.ClientId, c.Username, c.Password) + "
";
                    if (string.IsNullOrWhiteSpace(c.Username))
                    {
                        Message += string.Format("用户:{0}登录失败,用户信息为空", c.ClientId) + "
";

                        c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        return;
                    }
                    //解析用户名和密码,这个地方需要改成查找我们自己创建的用户名和密码。
                    if (c.Username == "admin" && c.Password == "123456")
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                        Message += c.ClientId + " 登录成功" + "
";
                        ClientInsTances.Add(new ClientInstance()
                        {
                            ClientID = c.ClientId,
                            UserName = c.Username,
                            PassWord = c.Password
                        });
                        return;
                    }
                    else
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        Message += "用户名密码错误登陆失败" + "
";
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("登录失败:" + ex.Message);
                    c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    return;
                }
            };
            //拦截订阅
            options.SubscriptionInterceptor = async context =>
            {
                try
                {
                    Message += "用户" + context.ClientId + "订阅" + "
";
                }
                catch (Exception ex)
                {
                    Console.WriteLine("订阅失败:" + ex.Message);
                    context.AcceptSubscription = false;
                }
            };
            //拦截消息
            options.ApplicationMessageInterceptor = context =>
            {
                try
                {
                    //一般不需要处理消息拦截
                    // Console.WriteLine(Encoding.UTF8.GetString(context.ApplicationMessage.Payload));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("消息拦截:" + ex.Message);
                }
            };

            mqttServer.ClientDisconnected += ClientDisconnected;
            mqttServer.ClientConnected += MqttServer_ClientConnected;
            mqttServer.Started += MqttServer_Started;
            mqttServer.StartAsync(options);

        }


        private void MqttServer_Started(object sender, EventArgs e)
        {
            Message += "消息服务启动成功:任意键退出" + "
";
        }

        private void MqttServer_ClientConnected(object sender, MqttClientConnectedEventArgs e)
        {
            //客户端链接
            Message += e.ClientId + "连接" + "
";
        }

        private void ClientDisconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            //客户端断开
            Message += e.ClientId + "断开" + "
";
        }

        /// <summary>
        /// 客户端推送信息    -  用于测试服务推送
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="message"></param>
        public void SendMessage(string clientID, string message)
        {
            mqttServer.PublishAsync(new MqttApplicationMessage
            {
                Topic = clientID,
                QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
                Retain = false,
                Payload = Encoding.UTF8.GetBytes(message),
            });
        }
    }

添加MQTT 客户端登陆实例, 用于保存客户的登陆信息,如下:

演示界面:

    /// <summary>
    /// 登陆客户端信息
    /// </summary>
    public class ClientInstance : ViewModelBase
    {
        private string clientID;
        private string userName;
        private string passWord;

        /// <summary>
        /// 识别ID
        /// </summary>
        public string ClientID
        {
            get { return clientID; }
            set { clientID = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 账户
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }


    }

MQTT客户端建立:

演示代码:

public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            clientID = new Random().Next(999, 9999) + ""; //测试随机生成ClientID
        }

        IMqttClient mqttClient;  //MQTT客户端实例

        string clientID; //机器ID


        string message;

        public string Message  //用于接收当前 消息
        {
            get { return message; }
            set { message = value; RaisePropertyChanged(); }
        }
        //开启MQTT连接
        public async void SignMqttServer()
        {
            var options = new MqttClientOptionsBuilder()
             .WithClientId(clientID) //传递ClientID 
             .WithTcpServer("127.0.0.1", 1883)  //MQTT服务的地址
             .WithCredentials("admin", "123456") //传递账号密码
             .WithCleanSession()
             .Build();
            mqttClient = new MqttFactory().CreateMqttClient();// .CreateManagedMqttClient();
            mqttClient.Connected += MqttClient_Connected;
            mqttClient.Disconnected += MqttClient_Disconnected;
            mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; //创建消息接受事件

            await mqttClient.ConnectAsync(options);
            //await mqttClient.SubscribeAsync(clientID);
        }

        private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Message += "收到的信息:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload) + "
";
        }

        private void MqttClient_Disconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            Message += "客户端断开";
        }

        private void MqttClient_Connected(object sender, MqttClientConnectedEventArgs e)
        {
            Message += "客户端已连接" + "
";
            mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(clientID).Build()); //关联服务端订阅, 用于接受服务端推送信息

        }
    }

演示界面:

C#实现MQTT服务端与客户端通讯功能

实际演示效果(GIF)

C#实现MQTT服务端与客户端通讯功能

到此这篇关于C#实现MQTT服务端与客户端通讯功能的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/zh7791/p/9439926.html

延伸 · 阅读

精彩推荐
  • C#C#编写Windows服务程序详细步骤详解(图文)

    C#编写Windows服务程序详细步骤详解(图文)

    本文介绍了如何用C#创建、安装、启动、监控、卸载简单的Windows Service 的内容步骤和注意事项,需要的朋友可以参考下...

    C#教程网6032022-01-22
  • C#C# 引入委托的目的是什么

    C# 引入委托的目的是什么

    这篇文章主要介绍了C# 引入委托的目的是什么,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    Learning hard9612022-09-28
  • C#C#实现简单俄罗斯方块

    C#实现简单俄罗斯方块

    这篇文章主要为大家详细介绍了C#实现简单俄罗斯方块,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    q6459896378902022-08-29
  • C#Unity实现跑马灯抽奖效果

    Unity实现跑马灯抽奖效果

    这篇文章主要为大家详细介绍了Unity实现跑马灯抽奖效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Sweet_james7422022-03-10
  • C#C#正方形图片的绘制方法

    C#正方形图片的绘制方法

    这篇文章主要为大家详细介绍了C#正方形图片的绘制方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    薛定谔家的猫12232022-03-02
  • C#C#实现将程序运行信息写入日志的方法

    C#实现将程序运行信息写入日志的方法

    这篇文章主要介绍了C#实现将程序运行信息写入日志的方法,可实现将程序运行信息写入日志并存储在Debug目录下的"/Log/PRG"下的功能,涉及C#针对日志的相关写...

    北风其凉8192021-10-19
  • C#C# ManualResetEvent用法详解

    C# ManualResetEvent用法详解

    这篇文章主要介绍了C# ManualResetEvent用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着...

    陌客&5042022-08-11
  • C#OpenXml合并Table单元格代码实例

    OpenXml合并Table单元格代码实例

    在本篇文章里小编给大家整理了关于OpenXml合并Table单元格的相关实例详解,需要的朋友们参考下。...

    dzw1596302022-08-01