MQTTnet入门(二) - 验证来自MQTT客户端的连接请求

5 篇文章 6 订阅

MQTTnet入门(二) - 验证来自MQTT客户端的连接请求

前言

通过《MQTTnet入门(一) - 创建最简易的MQTT服务器》中提供的Demo已经可以实现一个简易的MQTT服务了,但在MQTTnet的Server上还有很多的配置和接口可以允许我们继续开发,本文就验证来自客户端的连接请求的问题提供一个可行的Demo。

验证连接请求的MQTT服务器Demo

在Client请求建立连接时,我们可以通过接口获得一个MqttConnectionValidatorContext类型的对象,通过它我们能获得当前建立连接请求的基本参数,例如:ClientIdUsernamePassword 等。我们通过对这些参数的验证并依照验证结果修改ReasonCode 的状态值,即可实现我们的需求。

下面就是代码了:

using MQTTnet;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;

namespace MQTT
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            // 创建MQTT服务配置的构建器
            MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder();
            
            // 为构建器添加连接验证的处理过程
            optionsBuilder.WithConnectionValidator(context => {

                // 验证ClientID的长度
                if (context.ClientId.Length < 10)
                {
                    context.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }

                // 验证用户名和密码
                if (context.Username != "user01" || context.Password != "123456")
                {
                    context.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                // 标记当前连接请求的ReasonCode为Success
                context.ReasonCode = MqttConnectReasonCode.Success;
            });

            // 利用MqttFactory创建MQTT服务器
            IMqttServer mqttServer = new MqttFactory().CreateMqttServer();

            // 采用异步方式启动服务(使用服务配置构建器创建的对象)
            await mqttServer.StartAsync(optionsBuilder.Build());

            Console.WriteLine("按任意键退出程序...");
            Console.ReadLine();

            // 异步关闭MQTT服务
            await mqttServer.StopAsync();
        }
    }
}

在代码中预设了一个用户名为user01,密码为123456的账户,可在此替换成其他的验证方式,这里就不再啰嗦了。至此,验证来自MQTT客户端的连接请求的功能就添加完成了。MQTTnet.Server的更多功能可以参考附录中的API。


附录:MQTTnet API - Server

属性

客户端建立连接时的处理过程

Description: The connected handler to perform actions when a client connected.

数据类型:IMqttServerClientConnectedHandler
属性名:ClientConnectedHandler
默认值:null

客户端断开连接时的处理过程

Description: The disconnected handler to perform actions when a client lost the connection.

数据类型:IMqttServerClientDisconnectedHandler
属性名:ClientDisconnectedHandler
默认值:null

客户端在订阅主题时的处理过程

Description: The subscribed handler to perform actions when a client subscribed.

数据类型:IMqttServerClientSubscribedTopicHandler
属性名:ClientSubscribedTopicHandler
默认值:null

客户端在退订主题时的处理过程

Description: The subscribed handler to perform actions when a client unsubscribed.

数据类型:IMqttServerClientUnsubscribedTopicHandler
属性名:ClientUnsubscribedTopicHandler
默认值:null

服务器配置项

Description: The server options set to the client.

数据类型:IMqttServerOptions
属性名:Options
默认值:null

服务器启动时的处理过程

Description: The started handler to perform actions when the server started.

数据类型:IMqttServerStartedHandler
属性名:StartedHandler
默认值:null

服务器关闭后的处理过程

Description: The stopped handler to perform actions when the server stopped.

数据类型:IMqttServerStoppedHandler
属性名:StoppedHandler
默认值:null

方法

清除保留的应用程序消息

Description: Clears the retained application messages.

返回类型:Task
方法名:ClearRetainedApplicationMessagesAsync()

获取客户端状态

Description: Gets the client status.

返回类型:Task
方法名:GetClientStatusAsync()

获取保留的应用程序消息

Description: Gets the retained application messages.

返回类型:Task
方法名:GetRetainedApplicationMessagesAsync()

获取会话状态

Description: Gets the session status.

返回类型:Task
方法名:GetSessionStatusAsync()

启动服务器

Description: Starts the server.

返回类型:Task
方法名:StartAsync(IMqttServerOptions options)

停止服务器

Description: Stops the server.

返回类型:Task
方法名:StopAsync()

在服务器上为客户端订阅主题

Description: Subscribes the server to topics.

返回类型:Task
方法名:SubscribeAsync(string clientId, ICollection topicFilters)

在服务器上为客户端退订主题

Description: Unsubscribes the server from topics

返回类型:Task
方法名:UnsubscribeAsync(string clientId, ICollection topicFilters)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
paho.mqtt.embedded-c是一个C语言实现的MQTT客户库,它提供了MQTT协议的完整实现,可以运行在嵌入式系统中。如果你需要在C++项目中使用MQTT客户,可以使用paho.mqtt.embedded-c库的C++封装,也就是paho.mqtt.cpp库。 paho.mqtt.cpp库是一个基于paho.mqtt.embedded-c库的C++封装,它提供了更加易用的C++ API,使得在C++项目中使用MQTT更加方便。 下面是一个使用paho.mqtt.cpp库实现MQTT客户的示例代码: ```c++ #include <cstdlib> #include <iostream> #include <cstring> #include <chrono> #include <thread> #include "mqtt/async_client.h" const std::string SERVER_ADDRESS("tcp://localhost:1883"); const std::string CLIENT_ID("paho_cpp_async_subcribe"); const std::string TOPIC("hello"); class callback : public virtual mqtt::callback { public: virtual void connection_lost(const std::string& cause) override { std::cout << "Connection lost: " << cause << std::endl; } virtual void message_arrived(mqtt::const_message_ptr msg) override { std::cout << "Message arrived" << std::endl; std::cout << "Topic: " << msg->get_topic() << std::endl; std::cout << "Payload: " << msg->to_string() << std::endl; } virtual void delivery_complete(mqtt::delivery_token_ptr token) override { std::cout << "Delivery complete" << std::endl; } }; int main(int argc, char* argv[]) { mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID); callback cb; client.set_callback(cb); mqtt::connect_options conn_opts; conn_opts.set_keep_alive_interval(20); conn_opts.set_clean_session(true); std::cout << "Connecting to the MQTT server..." << std::flush; try { mqtt::token_ptr conntok = client.connect(conn_opts); conntok->wait(); std::cout << "OK" << std::endl; } catch (const mqtt::exception& exc) { std::cerr << "\nERROR: Unable to connect to MQTT server: " << exc.what() << std::endl; return 1; } mqtt::token_ptr subtok = client.subscribe(TOPIC, 0); subtok->wait(); std::cout << "Subscribed to topic: " << TOPIC << std::endl; while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); } client.unsubscribe(TOPIC)->wait(); client.disconnect()->wait(); return 0; } ``` 在这个示例代码中,我们使用了paho.mqtt.cpp库来连接MQTT服务器,订阅一个主题,然后等待消息的到来。当消息到来时,我们会打印出来消息的主题和内容。 如果你需要在C++项目中使用MQTT客户,paho.mqtt.cpp库会是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿长大人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值