前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MQTTnet 实现MQTT 客户端和服务端「建议收藏」

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

作者头像
全栈程序员站长
发布2022-09-12 20:12:39
2.5K0
发布2022-09-12 20:12:39
举报

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

服务端:

代码语言:javascript
复制
 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);
            }*/
        }
    }

客户端

代码语言:javascript
复制
    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 客户端和服务端「建议收藏」
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.cn/152900.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档