MessageDispatherComponentSystem.cs 2.3 KB

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