我是靠谱客的博主 忧伤钢铁侠,最近开发中收集的这篇文章主要介绍MQTT 服务端搭建以及详解,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  • 服务端配置
  1. 链接方法

创建MQTT服务器类似于创建MQTT客户机。下面的代码显示了创建一个新的MQTT服务器的最简单方法,该服务器的TCP端点正在默认端口1883上侦听。

// Configure MQTT server.
var optionsBuilder = new MqttServerOptionsBuilder()
    .WithConnectionBacklog(100)//最大链接数
    .WithDefaultEndpointPort(1883);//监听端口号

var mqttServer = new MqttFactory().CreateMqttServer();
mqttServer.StartAsync(optionsBuilder.Build());//服务启动

配置参数如下所示

函数名功能说明
Build构建配置参数
WithApplicationMessageInterceptor允许处理来自客户端的所有已发布消息
WithClientId服务端发布消息时使用的ClientId
WithConnectionBacklog设置要保留的连接数
WithConnectionValidator验证连接
WithDefaultCommunicationTimeout设置默认的通信超时
WithDefaultEndpoint使用默认端点
WithDefaultEndpointBoundIPAddress使用默认端点IPv4地址
WithDefaultEndpointBoundIPV6Address使用默认端点IPv6地址
WithDefaultEndpointPort使用默认端点端口
WithEncryptedEndpoint使用加密的端点
WithEncryptedEndpointBoundIPAddress使用加密的端点IPv4地址
WithEncryptedEndpointBoundIPV6Address使用加密的端点IPv6地址
WithEncryptedEndpointPort使用加密的端点端口
WithEncryptionCertificate使用证书进行SSL连接
WithEncryptionSslProtocol使用SSL协议级别
WithMaxPendingMessagesPerClient每个客户端允许最多未决消息
WithPersistentSessions保持会话
WithStorage使用存储
WithSubscriptionInterceptor允许处理来自客户端的所有订阅
WithoutDefaultEndpoint禁用默认端点
WithoutEncryptedEndpoint禁用默认(SSL)端点

账户验证

var optionsBuilder = new MqttServerOptionsBuilder()
    .WithConnectionValidator(c =>
{
    if (c.ClientId.Length < 10)
    {
        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
        return;
    }

    if (c.Username != "mySecretUser")
    {
        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
        return;
    }

    if (c.Password != "mySecretPassword")
    {
        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
        return;
    }

    c.ReasonCode = MqttConnectReasonCode.Success;
});

另一种验证账户方式

        mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(MqttClientConnectedEvent);

        /// <summary>
        /// 可以增加对客户端的校验规则
        /// </summary>
        /// <param name="e"></param>
        static void MqttClientConnectedEvent(MqttServerClientConnectedEventArgs e)
        {
            if (e.ClientId.Length < 10)
            {
                                    Console.WriteLine(MqttConnectReturnCode.ConnectionRefusedIdentifierRejected);
                
            }

            if (e.UserName != "gaodong")
            {
                Console.WriteLine(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword);
            }
        }

可以在服务器选项中设置自定义拦截器。对于服务器接收到的每个应用程序消息,都会调用该拦截器。这允许在应用程序消息被持久化(对于保留的消息)之前以及在被分派给订阅者之前扩展它们。这允许在硬件设备不知道时间或时区等情况下向每个应用程序消息添加时间戳。以下代码显示了如何使用拦截器:

var optionsBuilder = new MqttServerOptionsBuilder()
    .WithApplicationMessageInterceptor(context =>
    {
        if (context.ApplicationMessage.Topic == "my/custom/topic")
        {
            context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes("The server injected payload.");
        }

        // 可以像这样禁止发送特定客户端id的消息:
        if (context.ClientId != "Someone")
        {
            context.AcceptPublish = false;
            return;
        }
        // 还可以读取有效负载并扩展它。例如,在JSON文档中添加时间戳.
        // 当物联网设备没有自己的时钟且消息的创建时间可能很重要时,这很有用.
    })
    .Build();

拦截订阅

可以设置自定义拦截器来控制MQTT客户机可以订阅哪些主题。这允许将私有API主题移动到仅对某些客户端可用的受保护区域。下面的代码显示了如何使用订阅拦截器。

// 防止每个客户端订阅多个主题.
var optionsBuilder = new MqttServerOptionsBuilder()
    .WithSubscriptionInterceptor(context =>
    {
        if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
        {
            context.AcceptSubscription = false;
        }

        if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
        {
            context.AcceptSubscription = false;
            context.CloseConnection = true;
        }
    })
    .Build();

最后

以上就是忧伤钢铁侠为你收集整理的MQTT 服务端搭建以及详解的全部内容,希望文章能够帮你解决MQTT 服务端搭建以及详解所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部