MessageDispatherComponent.cs 2.1 KB

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