MessageDispatcherComponent.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public class MessageDispatcherComponentAwakeSystem : AwakeSystem<MessageDispatcherComponent>
  6. {
  7. public override void Awake(MessageDispatcherComponent t)
  8. {
  9. t.Awake();
  10. }
  11. }
  12. public class MessageDispatcherComponentLoadSystem : LoadSystem<MessageDispatcherComponent>
  13. {
  14. public override void Load(MessageDispatcherComponent self)
  15. {
  16. self.Load();
  17. }
  18. }
  19. /// <summary>
  20. /// 消息分发组件
  21. /// </summary>
  22. public class MessageDispatcherComponent : Entity
  23. {
  24. private readonly Dictionary<ushort, List<IMHandler>> handlers = new Dictionary<ushort, List<IMHandler>>();
  25. public void Awake()
  26. {
  27. this.Load();
  28. }
  29. public void Load()
  30. {
  31. this.handlers.Clear();
  32. HashSet<Type> types = Game.EventSystem.GetTypes(typeof(MessageHandlerAttribute));
  33. foreach (Type type in types)
  34. {
  35. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  36. if (attrs.Length == 0)
  37. {
  38. continue;
  39. }
  40. IMHandler iMHandler = Activator.CreateInstance(type) as IMHandler;
  41. if (iMHandler == null)
  42. {
  43. Log.Error($"message handle {type.Name} 需要继承 IMHandler");
  44. continue;
  45. }
  46. Type messageType = iMHandler.GetMessageType();
  47. ushort opcode = this.Parent.GetComponent<OpcodeTypeComponent>().GetOpcode(messageType);
  48. if (opcode == 0)
  49. {
  50. Log.Error($"消息opcode为0: {messageType.Name}");
  51. continue;
  52. }
  53. this.RegisterHandler(opcode, iMHandler);
  54. }
  55. }
  56. public void RegisterHandler(ushort opcode, IMHandler handler)
  57. {
  58. if (!this.handlers.ContainsKey(opcode))
  59. {
  60. this.handlers.Add(opcode, new List<IMHandler>());
  61. }
  62. this.handlers[opcode].Add(handler);
  63. }
  64. public void Handle(Session session, MessageInfo messageInfo)
  65. {
  66. List<IMHandler> actions;
  67. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  68. {
  69. Log.Error($"消息没有处理: {messageInfo.Opcode} {JsonHelper.ToJson(messageInfo.Message)}");
  70. return;
  71. }
  72. foreach (IMHandler ev in actions)
  73. {
  74. try
  75. {
  76. ev.Handle(session, messageInfo.Message).Coroutine();
  77. }
  78. catch (Exception e)
  79. {
  80. Log.Error(e);
  81. }
  82. }
  83. }
  84. public override void Dispose()
  85. {
  86. if (this.IsDisposed)
  87. {
  88. return;
  89. }
  90. base.Dispose();
  91. }
  92. }
  93. }