Net Core Mqtt

该代码段展示了如何在.NET环境中创建并配置一个Mqtt服务器,包括设置IP地址、端口和超时时间。同时,它实现了连接管理器,处理客户端的连接、断开、订阅和取消订阅等事件。服务还包括了连接验证的处理函数。
摘要由CSDN通过智能技术生成
 /// <summary>
    ///  开启Mqtt 服务
    /// </summary>
    public static class StartMqttServerMethods
    {
        public class MqttServerOption
        {
            public string HostIp { get; set; }

            public int Port { get; set; }

            public int TimeOut { get; set; }

            public string ServerUserName { get; set; }

            public string ServerPassWord { get; set; }
        }

        public static void AddPkspMqttServers(this IServiceCollection services, MqttServerOption mqttServerOption)
        {
            IMqttServer server = new MqttFactory().CreateMqttServer();

            var optionBuilder = new MqttServerOptionsBuilder()
              .WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse(mqttServerOption.HostIp))
              .WithDefaultEndpointPort(mqttServerOption.Port)
              .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(mqttServerOption.TimeOut));

            var option = optionBuilder.Build();
            services.AddHostedMqttServerEx(option);
            services
               .AddHostedMqttServer(option)
               .AddMqttConnectionHandler()
               .AddMqttWebSocketServerAdapter()
               .AddMqttTcpServerAdapter()
               .AddConnections()
               ;
            //await server.StartAsync(option);
        }

        public static async void UseConnectionManager(this IMqttServer mqttServer, IApplicationBuilder app, MqttServerOption mqttServerOption)
        {
            var connectionManager = app.ApplicationServices.GetService<ConnectionManager>();
            mqttServer.ClientConnectedHandler = connectionManager;
            mqttServer.ClientDisconnectedHandler = connectionManager;
            mqttServer.ClientSubscribedTopicHandler = connectionManager;
            mqttServer.ClientUnsubscribedTopicHandler = connectionManager;
        }
  public class ConnectionManager : IMqttServerClientSubscribedTopicHandler, IMqttServerClientUnsubscribedTopicHandler, IMqttServerClientConnectedHandler, IMqttServerClientDisconnectedHandler, IMqttServerClientConnectionValidatorHandler
    {
        private IMqttServer mqttServer;
        private IJwtUtils _jwtUtils;
        private IMemoryCache _memoryCache;
        public Func<MqttConnectionValidatorContext, Task> _callback;

        public ConnectionManager(IMemoryCache memoryCache, IMqttServer mqttServers, IJwtUtils jwtUtils)
        {
            mqttServer = mqttServers;
            _jwtUtils = jwtUtils;
            _memoryCache = memoryCache;

            //   ServiceLocator.Instance.GetService<IJwtUtils>();
        }

        public async Task HandleClientSubscribedTopicAsync(MqttServerClientSubscribedTopicEventArgs eventArgs)
        {
            //SystemUserDto systemUser=(SystemUserDto)_memoryCache.Get(_jwtUtils.GetCurrentUserInfo().Id);
            //systemUser.
            //Console.WriteLine($"客户端:{eventArgs.ClientId}");
            //Console.WriteLine($"订阅主题:{eventArgs.TopicFilter.Topic}");
            //  await mqttServer.PublishAsync(eventArgs.TopicFilter.Topic, "欢迎登录");
            //return Task.CompletedTask;
        }

        public async Task HandleClientUnsubscribedTopicAsync(MqttServerClientUnsubscribedTopicEventArgs eventArgs)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"客户端:{eventArgs.ClientId}");
                Console.WriteLine($"取消订阅主题:{eventArgs.TopicFilter}");
            });
        }

        public async Task HandleClientDisconnectedAsync(MqttServerClientDisconnectedEventArgs eventArgs)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("退出");
                GC.Collect();
                GC.WaitForPendingFinalizers();
            });
        }

        public async Task HandleClientConnectedAsync(MqttServerClientConnectedEventArgs eventArgs)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("连接");
            });
        }

        public async Task HandleClientConnectionValidatorAsync(MqttServerClientConnectionValidatorEventArgs eventArgs)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("进入验证");
            });
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值