MessageDispatherComponent.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Model
  4. {
  5. [ObjectSystem]
  6. public class MessageDispatherComponentSystem : ObjectSystem<MessageDispatherComponent>, IAwake, ILoad
  7. {
  8. public void Awake()
  9. {
  10. this.Get().Awake();
  11. }
  12. public void Load()
  13. {
  14. this.Get().Load();
  15. }
  16. }
  17. /// <summary>
  18. /// 消息分发组件
  19. /// </summary>
  20. public class MessageDispatherComponent : Component
  21. {
  22. private Dictionary<Type, List<IMHandler>> handlers;
  23. public void Awake()
  24. {
  25. this.Load();
  26. }
  27. public void Load()
  28. {
  29. AppType appType = this.Entity.GetComponent<StartConfigComponent>().StartConfig.AppType;
  30. this.handlers = new Dictionary<Type, List<IMHandler>>();
  31. Type[] types = DllHelper.GetMonoTypes();
  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 = (MessageHandlerAttribute)attrs[0];
  40. if (!messageHandlerAttribute.Type.Is(appType))
  41. {
  42. continue;
  43. }
  44. object obj = Activator.CreateInstance(type);
  45. IMHandler imHandler = obj as IMHandler;
  46. if (imHandler == null)
  47. {
  48. throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
  49. }
  50. Type messageType = imHandler.GetMessageType();
  51. if (!this.handlers.TryGetValue(messageType, out List<IMHandler> list))
  52. {
  53. list = new List<IMHandler>();
  54. this.handlers.Add(messageType, list);
  55. }
  56. list.Add(imHandler);
  57. }
  58. }
  59. public void Handle(Session session, uint rpcId, IMessage message)
  60. {
  61. if (!this.handlers.TryGetValue(message.GetType(), out List<IMHandler> actions))
  62. {
  63. Log.Error($"消息 {message.GetType().FullName} 没有处理");
  64. return;
  65. }
  66. foreach (IMHandler ev in actions)
  67. {
  68. try
  69. {
  70. ev.Handle(session, rpcId, message);
  71. }
  72. catch (Exception e)
  73. {
  74. Log.Error(e.ToString());
  75. }
  76. }
  77. }
  78. public override void Dispose()
  79. {
  80. if (this.Id == 0)
  81. {
  82. return;
  83. }
  84. base.Dispose();
  85. }
  86. }
  87. }