MessageDispatherComponent.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Model
  4. {
  5. [ObjectSystem]
  6. public class MessageDispatherComponentAwakeSystem : AwakeSystem<MessageDispatherComponent>
  7. {
  8. public override void Awake(MessageDispatherComponent self)
  9. {
  10. self.Awake();
  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 class MessageDispatherComponent : Component
  25. {
  26. private Dictionary<Type, List<IMHandler>> handlers;
  27. public void Awake()
  28. {
  29. this.Load();
  30. }
  31. public void Load()
  32. {
  33. AppType appType = this.Entity.GetComponent<StartConfigComponent>().StartConfig.AppType;
  34. this.handlers = new Dictionary<Type, List<IMHandler>>();
  35. Type[] types = DllHelper.GetMonoTypes();
  36. foreach (Type type in types)
  37. {
  38. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  39. if (attrs.Length == 0)
  40. {
  41. continue;
  42. }
  43. MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
  44. if (!messageHandlerAttribute.Type.Is(appType))
  45. {
  46. continue;
  47. }
  48. object obj = Activator.CreateInstance(type);
  49. IMHandler imHandler = obj as IMHandler;
  50. if (imHandler == null)
  51. {
  52. throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
  53. }
  54. Type messageType = imHandler.GetMessageType();
  55. if (!this.handlers.TryGetValue(messageType, out List<IMHandler> list))
  56. {
  57. list = new List<IMHandler>();
  58. this.handlers.Add(messageType, list);
  59. }
  60. list.Add(imHandler);
  61. }
  62. }
  63. public void Handle(Session session, uint rpcId, IMessage message)
  64. {
  65. if (!this.handlers.TryGetValue(message.GetType(), out List<IMHandler> actions))
  66. {
  67. Log.Error($"消息 {message.GetType().FullName} 没有处理");
  68. return;
  69. }
  70. foreach (IMHandler ev in actions)
  71. {
  72. try
  73. {
  74. ev.Handle(session, rpcId, message);
  75. }
  76. catch (Exception e)
  77. {
  78. Log.Error(e.ToString());
  79. }
  80. }
  81. }
  82. public override void Dispose()
  83. {
  84. if (this.IsDisposed)
  85. {
  86. return;
  87. }
  88. base.Dispose();
  89. }
  90. }
  91. }