MessageDispatcherComponentSystem.cs 2.9 KB

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