MessageDispatherComponent.cs 2.1 KB

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