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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Wannacry(永恒之蓝)病毒「建议收藏」

    Wannacry(永恒之蓝)病毒「建议收藏」一、Wannacry(永恒之蓝)病毒2017.04-051)一种“蠕虫式”的勒索病毒软件,大小3.3MB,勒索病毒肆虐。2)由不法分子利用NSA(美国国家安全局)泄露的危险漏洞“EternalBlue”(永恒之蓝)进行传播。3)中国部分Windows操作系统用户遭受感染,校园网用户首当其冲,受害严重,大量实验室数据和毕业设计被锁定加密。部分大型企业的应用系统和数据库文件被加密后,无法正常工作,影响巨大。4)文件被加密,要求支付高比特币。5)比特币:比特币是一种P2P形式的虚拟的加密数字货币

    2022年10月17日
    3
  • linux基本命令iscsiadm,tgtadm和iscsiadm命令的用法

    linux基本命令iscsiadm,tgtadm和iscsiadm命令的用法:关联到指定lun上的后端存储设备,此例为分区-I–initiator-address:指定可以访问Target的IP地址具体用法请mantgtadm二.iscsiadm命令iscsiadm是个模式化的工具,其模式可通过-m或–mode选项指定,常见的模式有discoverydb、node、fw、session、host、iface几个,如果没有额外指定其它选项,则discoveryd…

    2022年8月23日
    12
  • 【python量化】用python搭建一个股票舆情分析系统

    【python量化】用python搭建一个股票舆情分析系统写在前面下面的这篇文章将手把手教大家搭建一个简单的股票舆情分析系统,其中将先通过金融界网站爬取指定股票在一段时间的新闻,然后通过百度情感分析接口,用于评估指定股票的正面和反面新闻的占比,以…

    2022年9月20日
    3
  • linux(1)Mac上传文件到Linux服务器

    linux(1)Mac上传文件到Linux服务器前言我们使用mac时,想让本地文件上传至服务器,该怎么办呢windows系统,我们可以使用xftp或者rz命令,那么mac呢?mac系统,我们可以使用sftp、scp或者rz命令,本文介绍sft

    2022年7月31日
    6
  • xamarin android listview的用法

    xamarin android listview的用法listview也许是用的非常频繁的一个控件之一,下面我写一个xamarin的listview栗子,大家尝一尝xamarinandroid开发的乐趣。原谅我的大小写吧.listview绑定自定义的BaseAdapter先来看一下最终实现的效果图:News.cs和NewAdapter.csnamespaceDrawerLayout.Adapter{public…

    2022年7月22日
    12
  • wireshark抓包工具详细说明及操作使用_wireshark ping抓包

    wireshark抓包工具详细说明及操作使用_wireshark ping抓包wireshark是非常流行的网络封包分析软件,功能十分强大。可以截取各种网络封包,显示网络封包的详细信息。使用wireshark的人必须了解网络协议,否则就看不懂wireshark了。为了安全考虑,wireshark只能查看封包,而不能修改封包的内容,或者发送封包。wireshark能获取HTTP,也能获取HTTPS,但是不能解密HTTPS,所以wireshark看不懂HTTPS中的

    2025年9月28日
    3

发表回复

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

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