MessageDispatherComponentSystem.cs 2.4 KB

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