使用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服务器

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

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

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

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

(0)
blank

相关推荐

  • LSM树详解_黑龙江野生鱼品种

    LSM树详解_黑龙江野生鱼品种LSM树(Log-Structured-Merge-Tree)的名字往往会给初识者一个错误的印象,事实上,LSM树并不像B+树、红黑树一样是一颗严格的树状数据结构,它其实是一种存储结构,目前HBase,LevelDB,RocksDB这些NoSQL存储都是采用的LSM树。LSM树的核心特点是利用顺序写来提高写性能,但因为分层(此处分层是指的分为内存和文件两部分)的设计会稍微降低读性能,但是通过牺牲小部分读性能换来高性能写,使得LSM树成为非常流行的存储结构。1、LSM树的核心思想如上图所示,LSM树有

    2022年10月29日
  • Sample rate 理解「建议收藏」

    Sample rate 理解「建议收藏」在Gnuradio中,我们可以看到很多模块中都有Samplerate这个概念然后看到一个说明 Anyprocessingblock’s’SampleRate’parameterisusedforDSPcalculation,notforcontrollingtherateatwhichsamplesareproduced.Thisisdis

    2022年10月17日
  • java反编译工具Java Decompiler

    java反编译工具Java Decompiler我想看一下jsp编译后生成的java文件,用记事本这些看的话要不就乱码,要不就看起来很乱,可读性很低百度了一下java反编译工具JavaDecompiler:这个工具不仅能反编译.class文件,将.class文件转换为可读的.java文件,而且还可以对整个jar包进行反编译。该工具不仅有自己的图形化界面工具JD-GUI,而且还有eclipse和IntelliJIDEA的…

  • word如何一键全选,word怎么全选所有内容(word文档的快捷键操作)「建议收藏」

    word如何一键全选,word怎么全选所有内容(word文档的快捷键操作)「建议收藏」全选快捷键能够提升我们在实际操作word时工作效能,在实际操作Word2003中如何对文本文档中的文本开展选中呢?下边为大伙儿出示几类选中的方式,肯定功能强大。Word如何选中?方式一、应用Word全选快捷键“CtrlA”开展选中(也适用excel表);方式二、进行工具栏中的“编写”,随后挑选“选中”按键来选中;方式三、运用电脑鼠标选中,鼠标左键按着没放随后拖拽到最终还可以选中;方式…

  • python 自带的word2vec讲解_word2vec训练

    python 自带的word2vec讲解_word2vec训练word2vec理解学习nlp最先了解的概念应该就是词嵌入(wordembedding)吧,Word2vec是谷歌于2013年提出的一种有效的词嵌入的方法,采用了两种模型(CBOW与skip-gram模型)与两种优化方法(负采样与层次softmax方法)的组合。现在使用Word2vec获得词的向量表达,并将其应用于各种nlp任务中已经非常常见。由于我们要用计算机来完成各种自然语言理解的任务,而…

  • 2021年社工必备查询网址汇总[通俗易懂]

    2021年社工必备查询网址汇总[通俗易懂]社工查询网站手机号注册网站查询信用查询国内企业信息政府信息查询身份信息查询驾驶员及车辆信息查询物品资产查询物流查询发票查询金融查询手机信息查询个人信息查询搜索引擎手机号注册网站查询牛查查http://www.newx007.com比REG007更好用的查询手机注册网站的神器信用查询1、信用中国查询内容:工商注册企业和个人、行政许可和处罚网址:http://www.creditchina.gov.cn/2、全国企业信用信息公示查询内容:全国企业工商登记注册信息http://g

发表回复

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

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