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


相关推荐

  • jsplumb 绘制页面链接线

    jsplumb 绘制页面链接线最近公司打算实现通用的流程设计 对比之前公司有一套源码 发现它采用的是 FlowDesign 来实现的 但从晚上查找之后发现它实际上是采用了 jsplumb 来实现流程绘制的 这也不难理解 毕竟 jsplumb 是通用的程序 FlowDesign 只能算是 jsplumb 的具体使用 FlowDesign 的地址是 http flowdesign leipi org Jsplumb 官网 https

    2025年11月2日
    3
  • 关于YUV420

    关于YUV和RGB色彩模型一样,YUV也是被发明来描述色彩的模型。类似的还有CMYK等。RGB是使用红绿蓝三原色来描述色彩的模型。YUV使用亮度和色度来描述色彩的模型。CMYK是使用青色Cyan、品红色Magenta、黄色Yellow来描述色彩的模型。Y:表示的是亮度。UV是色差。YUV又称YCbCr,Cb代表蓝色差量(U),Cr代表红色分量(V),Y不仅有绿分量,还叠加了亮度信息。

    2022年4月9日
    42
  • 简单VBS教程「建议收藏」

    简单VBS教程「建议收藏」讲一下VBScript。主要面向菜鸟,懂得编程的朋友就不要浪费时间了,如果你想接触以下VBScript也可以。但既然有编程基础推荐直接去找一些参考书来读。会比较快。    什么是VBScript呢?VBScript的全称是:MicrosoftVisualBasicScriptEditon.(微软公司可视化BASIC脚本版)。正如其字面所透露的信息,VBS(VBScript的进一步简写)是基…

    2022年6月12日
    28
  • Quartus II 操作入门[通俗易懂]

    Quartus II 操作入门[通俗易懂]使用Quartus设计FPGA,简单包括以下流程:新建工程,写代码编译工程,找错误分配引脚,重编译下载配置,到硬件为保证设计的正确性,在编译后,一般还需要做仿真验证,然后下载至硬件,有两种仿真方式:-功能仿真-时序仿真新建工程,写代码创建工程文件夹在电脑上新建一个文件夹,例如E:\Lianxi_1。工程的文件将全都存在这个文件夹内,便于管理。一个工程对应一个文件夹。新建

    2022年10月15日
    2
  • IDEA优化内存配置,可提高启动和运行速度(亲测有效)「建议收藏」

    IDEA优化内存配置,可提高启动和运行速度(亲测有效)「建议收藏」一、优化IDEA配置IDEA默认启动配置主要考虑低配置用户,参数不高(默认最低128m,最高512m),导致启动慢,然后运行也不流畅,这里我们需要优化下启动和运行配置;但是在工作中的电脑一般都是8G或者16G的运行内存,所以我们需要手动去修改默认的IDEA配置。二、手动修改IDEA配置步骤找到IDEA安装的bin目录打开idea.exe.vmoptions文件关键的三个参…

    2022年5月20日
    716
  • PhantomJS简介[通俗易懂]

    PhantomJS简介[通俗易懂]PhantomJS是一个可编程的无头浏览器.无头浏览器:一个完整的浏览器内核,包括js解析引擎,渲染引擎,请求处理等,但是不包括显示和用户交互页面的浏览器。可以使用Phantomejs做一些页面渲染的工作;如获取js的页面内容、截图等;

    2022年7月26日
    9

发表回复

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

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