前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[C#] Blazor练习 依赖注入2

[C#] Blazor练习 依赖注入2

作者头像
科控物联
发布2022-12-01 10:54:30
5600
发布2022-12-01 10:54:30
举报
文章被收录于专栏:科控自动化

[C#] Blazor练习 依赖注入

注册可注入依赖项

注入依赖

代码语言:javascript
复制
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Server;
using System;
using System.Text;
using System.Threading.Tasks;
using MQTTnet.Client.Receiving;
using System.Collections.Generic;


namespace MqttBrokerWithDashboard.MqttBroker
{
    public class MqttBrokerService : IMqttServerClientConnectedHandler, IMqttServerClientDisconnectedHandler, IMqttApplicationMessageReceivedHandler, IMqttServerClientMessageQueueInterceptor
    {
        readonly ILogger _log;

        public IMqttServer Server { get; set; }

        readonly object _thisLock = new();

        List<MqttMessage> _messages = new();
        public IReadOnlyList<MqttMessage> Messages
        {
            get
            {
                lock (_thisLock)
                {
                    return _messages?.AsReadOnly();
                }
            }
        }

         Dictionary<string, List<MqttMessage>> _messagesByTopic = new();
        // MemoryCache _messagesByTopic = new MemoryCache();

        public IReadOnlyDictionary<string, List<MqttMessage>> MessagesByTopic
        {
            get
            {
                lock (_thisLock)
                {
                    return _messagesByTopic as IReadOnlyDictionary<string, List<MqttMessage>>;
                }
            }
        }

        List<MqttClient> _connectedClients = new();
        public IReadOnlyList<MqttClient> ConnectedClients
        {
            get
            {
                lock (_thisLock)
                {
                    return _connectedClients?.AsReadOnly();
                }
            }
        }


        public event Action<MqttServerClientConnectedEventArgs> OnClientConnected;
        public event Action<MqttServerClientDisconnectedEventArgs> OnClientDisconnected;
        public event Action<MqttApplicationMessageReceivedEventArgs> OnMessageReceived;


        public MqttBrokerService(ILogger<MqttBrokerService> log) =>
            _log = log;


        Task IMqttServerClientConnectedHandler.HandleClientConnectedAsync(MqttServerClientConnectedEventArgs e)
        {
            lock (_thisLock) _connectedClients.Add(new MqttClient
            {
                TimeOfConnection = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                ClientId = e.ClientId,
                AllowSend = true,
                AllowReceive = true,
            });

            _log.LogInformation($"Client connected: {e.ClientId}");

            OnClientConnected?.Invoke(e);
            return Task.CompletedTask;
        }

        Task IMqttServerClientDisconnectedHandler.HandleClientDisconnectedAsync(MqttServerClientDisconnectedEventArgs e)
        {
            lock (_thisLock)
            {
                var client = _connectedClients.Find(x => x.ClientId == e.ClientId);
                if (client == null)
                {
                    _log.LogError($"Unkownd client disconnected: {e.ClientId}");
                    return Task.CompletedTask;
                }

                _connectedClients.Remove(client);
            }

            _log.LogInformation($"Client disconnected: {e.ClientId}");

            OnClientDisconnected?.Invoke(e);
            return Task.CompletedTask;
        }

        Task IMqttApplicationMessageReceivedHandler.HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            var topic = e.ApplicationMessage.Topic;
            var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);

            lock (_thisLock)
            {
                var client = _connectedClients.Find(x => x.ClientId == e.ClientId);
                var message = new MqttMessage
                {
                    Timestamp = DateTime.Now,
                    Client = client,
                    Topic = topic,
                    Payload = payload,
                    Original = e.ApplicationMessage,
                };
                if (_messages.Count >100){
                    _messages.RemoveAt(_messages.Count-1);
                }
                _messages.Insert(0, message);



                if (_messagesByTopic.ContainsKey(topic)){
                    if (_messagesByTopic[topic].Count >100){
                    _messagesByTopic[topic].RemoveAt(_messagesByTopic[topic].Count-1);
                    }
                    _messagesByTopic[topic].Insert(0,  message);
                    }
                else
                    _messagesByTopic[topic] = new List<MqttMessage> { message };


            }

            _log.LogInformation($"OnMessageReceived: {topic} {payload}");

            OnMessageReceived?.Invoke(e);
            return Task.CompletedTask;
        }

        Task IMqttServerClientMessageQueueInterceptor.InterceptClientMessageQueueEnqueueAsync(MqttClientMessageQueueInterceptorContext context)
        {

            return Task.CompletedTask;
        }


        public void Publish(MqttApplicationMessage message) =>
            _ = Server?.PublishAsync(message);

        public void Publish(string topic, byte[] payload, bool retain) =>
            Publish(new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(payload)
                .WithRetainFlag(retain)
                .Build());

        public void Publish(string topic, string payload, bool retain) =>
            Publish(new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(payload)
                .WithRetainFlag(retain)
                .Build());
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-11-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 科控物联 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 注册可注入依赖项
  • 注入依赖
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档