MessageDispatherComponentSystem.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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.Instace = 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.Instace = 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, MessageInfo messageInfo)
  67. {
  68. List<IMHandler> actions;
  69. if (!self.Handlers.TryGetValue(messageInfo.Opcode, out actions))
  70. {
  71. Log.Error($"消息没有处理: {messageInfo.Opcode} {JsonHelper.ToJson(messageInfo.Message)}");
  72. return;
  73. }
  74. foreach (IMHandler ev in actions)
  75. {
  76. try
  77. {
  78. ev.Handle(session, messageInfo.Message);
  79. }
  80. catch (Exception e)
  81. {
  82. Log.Error(e);
  83. }
  84. }
  85. }
  86. }
  87. }