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

 

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 【OpenCV】双线性插值法

    【OpenCV】双线性插值法双线性插值法定义:又称双线性内插。在数学上,双线性插值是有两个变量的插值函数的线性插值扩展,其核心思想是在两个方向上分别进行一次线性插值。对于一个目的像素,设置坐标通过反向变换得到的浮点坐标为(i+u,j+v)(其中i、j均为浮点坐标的整数部分,u、v为浮点坐标的小数部分,是取值[0,1)区间的浮点数),则这个像素得值f(i+u,j+v)可由原图像中坐标为(i,j)、(…

  • Java关键字(50个)(超详细!)[通俗易懂]

    Java关键字(50个)(超详细!)[通俗易懂]关键字大致含义abstract表明类或者成员方法具有抽象属性assert断言,用来进行程序调试boolean基本数据类型之一,声明布尔类型的关键字break提前跳出一个块byte基本数据类型之一,字节类型case用在switch语句之中,表示其中的一个分支…

  • StringBuilder常用方法[通俗易懂]

    StringBuilder常用方法[通俗易懂]+构造函数StringBuilder()构造一个字符串生成器,其中没有字符,初始容量为16个字符。StringBuilder(CharSequenceseq)构造一个包含与指定字符相同的字符串的字符串构建器CharSequence。StringBuilder(intcapacity)构造一个不包含字符的字符串构建器以及capacity参数指定的初始容量。String…

  • native2ascii 用法_hex转ascii 在线

    native2ascii 用法_hex转ascii 在线native2ascii插件org.codehaus.mojonative2ascii-maven-plugin1.0-beta-1UTF-8src/main/resources/${message.dir.rel}${outputDirectory}/${message.dir.rel}**/*.propertiesnative2asc

  • Keras学习率调整

    Keras学习率调整Keras提供两种学习率适应方法,可通过回调函数实现。1.LearningRateSchedulerkeras.callbacks.LearningRateScheduler(schedule)该回调函数是学习率调度器.参数schedule:函数,该函数以epoch号为参数(从0算起的整数),返回一个新学习率(浮点数)代码importkeras.backenda…

  • SpringBoot Test及注解详解

    SpringBoot Test及注解详解一、SpringBootTest介绍SpringTest与JUnit等其他测试框架结合起来,提供了便捷高效的测试手段。而SpringBootTest是在SpringTest之上的再次封装,增加了切片测试,增强了mock能力。整体上,SpringBootTest支持的测试种类,大致可以分为如下三类:单元测试:一般面向方法,编写一般业务代码时,测试成本较大。涉及到的注解有@Test。 切片测试:一般面向难于测试的边界功能,介于单元测试和功能测试之间。涉及到的注解有@RunWith

发表回复

您的电子邮箱地址不会被公开。

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