MessageDispatherComponent.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using Model;
  4. namespace Hotfix
  5. {
  6. /// <summary>
  7. /// 消息分发组件
  8. /// </summary>
  9. [ObjectEvent(EntityEventId.MessageDispatherComponent)]
  10. public class MessageDispatherComponent: Component, IAwake, ILoad
  11. {
  12. private Dictionary<ushort, List<IMHandler>> handlers;
  13. public void Awake()
  14. {
  15. this.Load();
  16. }
  17. public void Load()
  18. {
  19. this.handlers = new Dictionary<ushort, List<IMHandler>>();
  20. Type[] types = DllHelper.GetHotfixTypes();
  21. foreach (Type type in types)
  22. {
  23. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  24. if (attrs.Length == 0)
  25. {
  26. continue;
  27. }
  28. MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
  29. IMHandler iMHandler = (IMHandler)Activator.CreateInstance(type);
  30. if (!this.handlers.ContainsKey(messageHandlerAttribute.Opcode))
  31. {
  32. this.handlers.Add(messageHandlerAttribute.Opcode, new List<IMHandler>());
  33. }
  34. this.handlers[messageHandlerAttribute.Opcode].Add(iMHandler);
  35. }
  36. }
  37. public void Handle(Session session, MessageInfo messageInfo)
  38. {
  39. if (!this.handlers.TryGetValue(messageInfo.Opcode, out List<IMHandler> actions))
  40. {
  41. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  42. return;
  43. }
  44. foreach (IMHandler ev in actions)
  45. {
  46. try
  47. {
  48. ev.Handle(session, messageInfo);
  49. }
  50. catch (Exception e)
  51. {
  52. Log.Error(e.ToString());
  53. }
  54. }
  55. }
  56. public override void Dispose()
  57. {
  58. if (this.Id == 0)
  59. {
  60. return;
  61. }
  62. base.Dispose();
  63. }
  64. }
  65. }