MessageDispatherComponentSystem.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using ETModel;
  4. namespace ETHotfix
  5. {
  6. [ObjectSystem]
  7. public class MessageDispatcherComponentAwakeSystem : AwakeSystem<MessageDispatcherComponent>
  8. {
  9. public override void Awake(MessageDispatcherComponent self)
  10. {
  11. MessageDispatcherComponent.Instace = self;
  12. self.Load();
  13. }
  14. }
  15. [ObjectSystem]
  16. public class MessageDispatcherComponentLoadSystem : LoadSystem<MessageDispatcherComponent>
  17. {
  18. public override void Load(MessageDispatcherComponent self)
  19. {
  20. self.Load();
  21. }
  22. }
  23. [ObjectSystem]
  24. public class MessageDispatcherComponentDestroySystem: DestroySystem<MessageDispatcherComponent>
  25. {
  26. public override void Destroy(MessageDispatcherComponent self)
  27. {
  28. MessageDispatcherComponent.Instace = null;
  29. self.Handlers.Clear();
  30. }
  31. }
  32. /// <summary>
  33. /// 消息分发组件
  34. /// </summary>
  35. public static class MessageDispatcherComponentHelper
  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, MessageInfo messageInfo)
  68. {
  69. List<IMHandler> actions;
  70. if (!self.Handlers.TryGetValue(messageInfo.Opcode, out actions))
  71. {
  72. Log.Error($"消息没有处理: {messageInfo.Opcode} {JsonHelper.ToJson(messageInfo.Message)}");
  73. return;
  74. }
  75. foreach (IMHandler ev in actions)
  76. {
  77. try
  78. {
  79. ev.Handle(session, messageInfo.Message);
  80. }
  81. catch (Exception e)
  82. {
  83. Log.Error(e);
  84. }
  85. }
  86. }
  87. }
  88. }