使用MQTTnet搭建Mqtt服务器

使用MQTTnet搭建Mqtt服务器官方介绍:MQTTnetMQTTnetisahighperformance.NETlibraryforMQTTbasedcommunication.ItprovidesaMQTTclientandaMQTTserver(broker).Theimplementationisbasedonthedocumentationfrom h…

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

使用MQTTnet搭建Mqtt服务器

官方介绍:

MQTTnet

MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.

Features

General

  • Async support
  • TLS 1.2 support for client and server (but not UWP servers)
  • Extensible communication channels (i.e. In-Memory, TCP, TCP+TLS, WS)
  • Lightweight (only the low level implementation of MQTT, no overhead)
  • Performance optimized (processing ~70.000 messages / second)*
  • Interfaces included for mocking and testing
  • Access to internal trace messages
  • Unit tested (~90 tests)

* Tested on local machine (Intel i7 8700K) with MQTTnet client and server running in the same process using the TCP channel. The app for verification is part of this repository and stored in /Tests/MQTTnet.TestApp.NetCore.

Client

  • Communication via TCP (+TLS) or WS (WebSocket) supported
  • Included core MqttClient with low level functionality
  • Also included ManagedMqttClient which maintains the connection and subscriptions automatically. Also application messages are queued and re-scheduled for higher QoS levels automatically.
  • Rx support (via another project)
  • Compatible with Microsoft Azure IoT Hub

Server (broker)

  • List of connected clients available
  • Supports connected clients with different protocol versions at the same time
  • Able to publish its own messages (no loopback client required)
  • Able to receive every message (no loopback client required)
  • Extensible client credential validation
  • Retained messages are supported including persisting via interface methods (own implementation required)
  • WebSockets supported (via ASP.NET Core 2.0, separate nuget)
  • A custom message interceptor can be added which allows transforming or extending every received application message
  • Validate subscriptions and deny subscribing of certain topics depending on requesting clients

Supported frameworks

  • .NET Standard 1.3+
  • .NET Core 1.1+
  • .NET Core App 1.1+
  • .NET Framework 4.5.2+ (x86, x64, AnyCPU)
  • Mono 5.2+
  • Universal Windows Platform (UWP) 10.0.10240+ (x86, x64, ARM, AnyCPU, Windows 10 IoT Core)
  • Xamarin.Android 7.5+
  • Xamarin.iOS 10.14+

Supported MQTT versions

  • 5.0.0 (planned)
  • 3.1.1
  • 3.1.0

Nuget

This library is available as a nuget package: https://www.nuget.org/packages/MQTTnet/

 

创建项目 

使用vs创建mqtt项目,选择winform项目,方便创建界面,查看相关数据信息。项目包括两个,server和client。

使用MQTTnet搭建Mqtt服务器

 服务器端界面结构如下:

使用MQTTnet搭建Mqtt服务器

Server在程序中添加本机IP:

var ips = Dns.GetHostAddressesAsync(Dns.GetHostName());

foreach (var ip in ips.Result)
{
    switch (ip.AddressFamily)
    {
        case AddressFamily.InterNetwork:
           TxbServer.Text = ip.ToString();
           break;
        case AddressFamily.InterNetworkV6:
           break;
     }
}

 添加一个Action ,用来想listbox中添加数据:

private Action<string> _updateListBoxAction;


//在load方法中定义
//超过1000条数据时,自动删除第一个
//出现滚动条时,滚动条自动向下移动
_updateListBoxAction = new Action<string>((s) =>
{
    listBox1.Items.Add(s);
    if (listBox1.Items.Count > 1000)
    {
        listBox1.Items.RemoveAt(0);
    }
    var visibleItems = listBox1.ClientRectangle.Height/listBox1.ItemHeight;

    listBox1.TopIndex = listBox1.Items.Count - visibleItems + 1;
});


//添加按键事件,按c时清空listbox
listBox1.KeyPress += (o, args) =>
{
    if (args.KeyChar == 'c' || args.KeyChar=='C')
    {
         listBox1.Items.Clear();
    }
};

 mqttserver

        private async void MqttServer()
        {
            if (null != _mqttServer)
            {
                return;
            }

            var optionBuilder =
                new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(Convert.ToInt32(TxbPort.Text));

            if (!TxbServer.Text.IsNullOrEmpty())
            {
                optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(TxbServer.Text));
            }
            
            var options = optionBuilder.Build();
            
            
            (options as MqttServerOptions).ConnectionValidator += context =>
            {
                if (context.ClientId.Length < 10)
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    return;
                }
                if (!context.Username.Equals("admin"))
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }
                if (!context.Password.Equals("public"))
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }
                context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                
            };
            

            _mqttServer = new MqttFactory().CreateMqttServer();
            _mqttServer.ClientConnected += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $">Client Connected:ClientId:{args.ClientId},ProtocalVersion:");

                var s = _mqttServer.GetClientSessionsStatusAsync();
                label3.BeginInvoke(new Action(() => { label3.Text = $"连接总数:{s.Result.Count}"; }));
            };

            _mqttServer.ClientDisconnected += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"<Client DisConnected:ClientId:{args.ClientId}");
                var s = _mqttServer.GetClientSessionsStatusAsync();
                label3.BeginInvoke(new Action(() => { label3.Text = $"连接总数:{s.Result.Count}"; }));
            };

            _mqttServer.ApplicationMessageReceived += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction,
                    $"ClientId:{args.ClientId} Topic:{args.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} QualityOfServiceLevel:{args.ApplicationMessage.QualityOfServiceLevel}");

            };

            _mqttServer.ClientSubscribedTopic += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"@ClientSubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Topic} QualityOfServiceLevel:{args.TopicFilter.QualityOfServiceLevel}");
            };
            _mqttServer.ClientUnsubscribedTopic += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"%ClientUnsubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Length}");
            };

            _mqttServer.Started += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Start...");
            };

            _mqttServer.Stopped += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Stop...");
                
            };

            await _mqttServer.StartAsync(options);
        }

把mqttserver中定义的事件都进行了绑定

(options as MqttServerOptions).ConnectionValidator 为进行mqttclient连接时进行的验证工作

 

想要查看完整代码,请移步到gitee

https://gitee.com/sesametech-group/MqttNetSln

你感觉文章还可以,移步到gitee上给个star


使用MQTTnet搭建Mqtt服务器

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

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

(0)
上一篇 2022年6月25日 下午3:36
下一篇 2022年6月25日 下午3:36


相关推荐

  • Depix初体验

    Depix初体验前情提要这几天有一个同学给我发了一张马赛克图,问我能不能还原?图片如上。我一看,这被马成什么鬼样子了,谁能还原得了?不过我忽然想到,我在公众号上看到一个名字叫做”Depix”的Github项目。然而近期在Github上,又出现了一款号称能抹去马赛克让原图重现的神器,引发海内外热议。这款工具名为Depix,上线没几天就在GitHub上标星已超过一万多,截止目前累计分支也超过了1.3k个。让它火出圈子的,就是下面这张效果图:如图所示,第一行是打了一层巨厚马赛克完全像素化后的文本内容,看不出

    2022年6月30日
    87
  • scala 隐式转换

    scala 隐式转换文章目录作用解决什么问题使用implicits的一些规则3.1.1标记规则3.1.2范围规则3.1.3一次规则3.1.4优先规则3.1.5命名规则3.1.6编译器使用implicit的几种情况3.2隐含类型转换3.3转换被方法调用的对象3.3.1支持新的类型3.3.2模拟新的语法结构实验总结implicit基本含义隐式转换隐式转换的另一个优点是它们支持目标类型转换.隐式转换操作规则隐式参数和spring的依赖注入之前关系与区别隐式转换类(ImplicitClasses)隐式类

    2022年10月11日
    5
  • 推荐下载使用:金山词霸2009官方牛津版 + 激活成功教程补丁

    推荐下载使用:金山词霸2009官方牛津版 + 激活成功教程补丁2008-03-2909:04推荐下载使用:金山词霸2009官方牛津版+激活成功教程补丁《金山词霸2009牛津版》收词总量5,000,000,例句2,000,000余条,涉及语种包括中、日、英、韩

    2022年7月1日
    38
  • mysql中explain的用法_mysql substr用法

    mysql中explain的用法_mysql substr用法基于Mysql5.7版本的explain参数详解…Mysql官网相关参数解读一:idSELECT标识符1.id越大越先执行2.相同id,从从往下执行二:select_type1.SIMPLE:最简单的查询(没有关联查询没有子查询没有union的查询语句)2:PRIMARY:子查询最外层的查询语句3.SUBQUERY:子查询内层查询语句4.DERIVED:派生表查询,FROM后的不是表而是查询后的结果集5.UNION:union或unionall中的第二个以后的查询表6.U

    2022年8月31日
    11
  • Google earthios_初步探索的重要成果

    Google earthios_初步探索的重要成果一、申请使用1.GoogleEarthStudio(以下简称GES)需要申请才能使用,前往GoogleEarthStudio官网注册申请,审核时间较久.2.审核通过,填写信息时留下的邮箱会收到如下提醒3.在Chrome浏览器中打开网址https://earth.google.com/studio/,会看到如下截图二、启动页1.新建项目,有两种方式分别是Blan…

    2026年1月22日
    5
  • db2top命令详解「建议收藏」

    db2top命令详解「建议收藏」目录1.db2top命令语法2.db2top运行模式2.1交互模式2.2批量模式3.db2top监控模式3.1数据库监控(d)3.2表空间监控(t)3.3动态SQL监控(D)3.4会话监控(l)3.5缓存池监控(b)3.6锁监控(U)3.7表监控(T)3.8瓶颈监控(B)4.其他1.db2top命令语法可使用命令行db2top–h查看,这里就不做赘述了。2.db2top运行模式db2t…

    2025年12月7日
    4

发表回复

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

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