MessageDispatherComponent.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Model
  4. {
  5. [ObjectEvent]
  6. public class MessageDispatherComponentEvent : ObjectEvent<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<ushort, List<IMHandler>> handlers;
  23. public void Awake()
  24. {
  25. this.Load();
  26. }
  27. public void Load()
  28. {
  29. handlers = new Dictionary<ushort, List<IMHandler>>();
  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 = (MessageHandlerAttribute)attrs[0];
  39. IMHandler iMHandler = (IMHandler)Activator.CreateInstance(type);
  40. if (!this.handlers.ContainsKey(messageHandlerAttribute.Opcode))
  41. {
  42. this.handlers.Add(messageHandlerAttribute.Opcode, new List<IMHandler>());
  43. }
  44. this.handlers[messageHandlerAttribute.Opcode].Add(iMHandler);
  45. }
  46. }
  47. public void Handle(MessageInfo messageInfo)
  48. {
  49. List<IMHandler> actions;
  50. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  51. {
  52. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  53. return;
  54. }
  55. foreach (IMHandler ev in actions)
  56. {
  57. try
  58. {
  59. ev.Handle(messageInfo.Message);
  60. }
  61. catch (Exception e)
  62. {
  63. Log.Error(e.ToString());
  64. }
  65. }
  66. }
  67. public override void Dispose()
  68. {
  69. if (this.Id == 0)
  70. {
  71. return;
  72. }
  73. base.Dispose();
  74. }
  75. }
  76. }