MessageDispatherComponentSystem.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ETModel
  4. {
  5. [ObjectSystem]
  6. public class MessageDispatherComponentAwakeSystem : AwakeSystem<MessageDispatherComponent>
  7. {
  8. public override void Awake(MessageDispatherComponent self)
  9. {
  10. self.Load();
  11. }
  12. }
  13. [ObjectSystem]
  14. public class MessageDispatherComponentLoadSystem : LoadSystem<MessageDispatherComponent>
  15. {
  16. public override void Load(MessageDispatherComponent self)
  17. {
  18. self.Load();
  19. }
  20. }
  21. /// <summary>
  22. /// 消息分发组件
  23. /// </summary>
  24. public static class MessageDispatherComponentEx
  25. {
  26. public static void Load(this MessageDispatherComponent self)
  27. {
  28. self.Handlers.Clear();
  29. AppType appType = Game.Scene.GetComponent<StartConfigComponent>().StartConfig.AppType;
  30. Type[] types = DllHelper.GetMonoTypes();
  31. foreach (Type type in types)
  32. {
  33. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  34. if (attrs.Length == 0)
  35. {
  36. continue;
  37. }
  38. MessageHandlerAttribute messageHandlerAttribute = attrs[0] as MessageHandlerAttribute;
  39. if (!messageHandlerAttribute.Type.Is(appType))
  40. {
  41. continue;
  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 = Game.Scene.GetComponent<OpcodeTypeComponent>().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 MessageDispatherComponent 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 MessageDispatherComponent 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. }