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


相关推荐

  • .Net审计之.Net Json反序列化

    .Net审计之.NetJson反序列化前言偶然下遇到一个.NET下有意思的Json反序列化点,记录一下反序列化内容,直入主题。.NetJson常见序列化与反序列化NET中常见的数据格

    2021年12月13日
    53
  • tophat使用_tophat是什么意思

    tophat使用_tophat是什么意思概述:tophat是以bowtie2为核心的一款比对软件。tophat工作分两步:1.将reads用bowtie比对到参考基因组上。2.将unmapped-reads打断成更小的fragment

    2022年8月3日
    5
  • CreateJS-TweenJS文档翻译

    CreateJS-TweenJS文档翻译TweenJS 模块 TweenJS 提供了一个简单但强大的渐变界面 它支持渐变的数字对象属性 amp CSS 样式属性 并允许链接补间动画和行动结合起来 创造出复杂的序列 简单 tween 下面的示例渐变 1000ms 内将目标的 alpha 属性从 0 1 渐变 之后调用 handleComple 函数 target alpha 0 createjs Tween get targ

    2025年9月18日
    0
  • request.getParameter();的意思[通俗易懂]

    request.getParameter();的意思[通俗易懂]对于httprequrest的request.getParameter()的作用,之前我只是在用它而不知道它到底有什么作用,今天看了一遍文章突然明白了其中的意思。  大致的内容如下:这个form提交请求后,在你的action中Stringname=request.getparameter(“name”);那么name的值就是“哈哈”  它是一种取参数的方法。

    2025年7月5日
    2
  • Python 图像处理_图像处理的一般步骤

    Python 图像处理_图像处理的一般步骤Python图像处理基础对我个人而言使用Python图像处理意在取代matlab,集中化使用Python环境保证之后在机器学习和OpenCV的使用上具有一致性,虽然从实验室师兄师姐的口中得知Python的图像处理较之matlab相对复杂(应该只是代码量的问题),但我依然觉得学习python环境比较实用和高效。在进行Python图像处理之前,Pillow是不可或缺的实用性工具,pillow是Py

    2022年10月14日
    1
  • pycharm2021.5专业版最新激活码(最新序列号破解)[通俗易懂]

    pycharm2021.5专业版最新激活码(最新序列号破解),https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月18日
    121

发表回复

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

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