MessageDispatcherComponentSystem.cs 3.1 KB

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