MQTTnet 实现MQTT 客户端和服务端「建议收藏」

MQTTnet 实现MQTT 客户端和服务端「建议收藏」服务端:classProgram{privatestaticMqttServermqttServer=null;staticvoidMain(string[]args){MqttNetTrace.TraceMessagePublished+=MqttNetTrace_Trace…

大家好,又见面了,我是你们的朋友全栈君。

服务端:

 class Program
    {
        private static MqttServer mqttServer = null;

        static void Main(string[] args)
        {
            MqttNetTrace.TraceMessagePublished += MqttNetTrace_TraceMessagePublished;
            new Thread(StartMqttServer).Start();

            while (true)
            {
                var inputString = Console.ReadLine().ToLower().Trim();

                if (inputString == "exit")
                {
                    mqttServer?.StopAsync();
                    Console.WriteLine("MQTT服务已停止!");
                    break;
                }
                else if (inputString == "clients")
                {
                    foreach (var item in mqttServer.GetConnectedClients())
                    {
                        Console.WriteLine($"客户端标识:{item.ClientId},协议版本:{item.ProtocolVersion}");
                    }
                }
                else
                {
                    Console.WriteLine($"命令[{inputString}]无效!");
                }
            }
        }

        private static void StartMqttServer()
        {
            if (mqttServer == null)
            {
                try
                {
                    var options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            if (p.ClientId == "c001")
                            {
                                if (p.Username != "u001" || p.Password != "p001")
                                {
                                    return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                                }
                            }

                            return MqttConnectReturnCode.ConnectionAccepted;
                        }
                    };

                    mqttServer = new MqttServerFactory().CreateMqttServer(options) as MqttServer;
                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            mqttServer.StartAsync();
            Console.WriteLine("MQTT服务启动成功!");
        }

        private static void MqttServer_ClientConnected(object sender, MqttClientConnectedEventArgs e)
        {
            Console.WriteLine($"客户端[{e.Client.ClientId}]已连接,协议版本:{e.Client.ProtocolVersion}");
        }

        private static void MqttServer_ClientDisconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            Console.WriteLine($"客户端[{e.Client.ClientId}]已断开连接!");
        }

        private static void MqttServer_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($"客户端[{e.ClientId}]>> 主题:{e.ApplicationMessage.Topic} 负荷:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} Qos:{e.ApplicationMessage.QualityOfServiceLevel} 保留:{e.ApplicationMessage.Retain}");
        }

        private static void MqttNetTrace_TraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
        {
            /*Console.WriteLine($">> 线程ID:{e.ThreadId} 来源:{e.Source} 跟踪级别:{e.Level} 消息: {e.Message}");

            if (e.Exception != null)
            {
                Console.WriteLine(e.Exception);
            }*/
        }
    }

客户端

    class Program
    {
        private static MqttClient mqttClient = null;
        static string topic = "测试1/测试2/测试3";
        static void Main(string[] args)
        {

            mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
            mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
            mqttClient.Connected += MqttClient_Connected;
            mqttClient.Disconnected += MqttClient_Disconnected;

            var options = new MqttClientTcpOptions
            {
                Server = "127.0.0.1",
                ClientId = Guid.NewGuid().ToString().Substring(0, 5),
                UserName = "u001",
                Password = "p001",
                CleanSession = true
            };

            mqttClient.ConnectAsync(options);
            Console.ReadLine();
            Console.WriteLine("Hello World!");
        }
        private static void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {

            Console.WriteLine($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");

        }
        private static void MqttClient_Connected(object sender, EventArgs e)
        {

            Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine);
            mqttClient.SubscribeAsync(new List<TopicFilter> {
                new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
            });
            Console.WriteLine($"已订阅[{topic}]主题" + Environment.NewLine);
            //开始发布消息
            string inputString = "你好么";
            var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
            mqttClient.PublishAsync(appMsg);
        }
        private static void MqttClient_Disconnected(object sender, EventArgs e)
        {

            Console.WriteLine("已断开MQTT连接!" + Environment.NewLine);

        }
    }

MQTTnet 实现MQTT 客户端和服务端「建议收藏」

MQTTnet 实现MQTT 客户端和服务端「建议收藏」

MQTTnet 实现MQTT 客户端和服务端「建议收藏」

MQTTnet 实现MQTT 客户端和服务端「建议收藏」

MQTTnet 实现MQTT 客户端和服务端「建议收藏」

 

源码下载地址:MQTT

MQTT Windows 端验证程序: http://mqttfx.jensd.de/index.php/download

                                                 https://download.csdn.net/download/kesshei/10906614

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/152900.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • vi/vim常用命令

    vi/vim常用命令ctrl+b上一页ctrl+f下一页ctrl+u上半页ctrl+d下半页H跳到屏幕的第一行M跳到屏幕的中间行L跳到屏幕的最后一行zt将光标所在的那一行移至屏幕顶部zb将光…

    2022年5月22日
    31
  • open 函数[通俗易懂]

    open 函数[通俗易懂]open函数用来打开一个文件open返回值为一个文件句柄,从操作系统托付给你的python程序,一旦处理完文件,需要归还句柄,只有这样你的程序不会超过一次能打开的文件句柄的数量上限withopen(‘photo.jpg’,’r+’)asf: jpgdata=f.read()open的第⼀个参数是⽂件名。第⼆个(mode打开模式)决定了这个⽂件如何被打开。如果你想读…

    2022年5月25日
    39
  • Centos7下安装Docker(详细安装教程)[通俗易懂]

    一,Docker简介百科说:Docker是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口。看起来有点雾,用过虚拟机的应该对虚拟化技术有点印象,不知道也没关系,就把它当成轻量级的虚拟机吧(虽然一个是完全虚拟化,一个是操作系统层虚拟化),这个解释到位:ht…

    2022年4月10日
    41
  • sql server 2008 r2产品密钥(附二)

    微软官方发布的MicrosoftSQLServer2008R2简体中文完整版。基于SQLServer2008提供可靠高效的智能数据平台构建而成,SQLServer2008R2提供了大量新改进,可帮助您的组织满怀信心地调整规模、提高IT效率并实现管理完善的自助BI。此版本中包含应用程序和多服务器管理、复杂事件处理、主数据服务及最终用户报告等方面的新功能和增强功能。…

    2022年4月11日
    64
  • spss中进行单因素方差分析的操作步骤是_双因素方差分析交互作用判断

    spss中进行单因素方差分析的操作步骤是_双因素方差分析交互作用判断方差分析是检验多个总体均值是否相等的统计方法,本质上研究的是分类型自变量对数值型因变量的影响。一:分析-比较均值-单因素方差分析;二、对比-多项式;在此对话框是用于对组间平方和进行分解并确定均值的

    2022年8月4日
    3
  • IntelliJ IDEA 详细图解最常用的配置 ,适合刚刚用的新人。

    IntelliJ IDEA 详细图解最常用的配置 ,适合刚刚用的新人。IntelliJIDEA使用教程(总目录篇)刚刚使用IntelliJIDEA编辑器的时候,会有很多设置,会方便以后的开发,磨刀不误砍柴工。比如:设置文件字体大小,代码自动完成提示,版本管理,本地代码历史,自动导入包,修改注释,修改tab的显示的数量和行数,打开项目方式,等等一大堆东西。总结一下,免得下次换了系统,还得再找一遍配置。具体总结如下图:设置外观和字体大小这…

    2022年5月21日
    41

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号