MessageDispatherComponent.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 readonly Dictionary<ushort, List<IMHandler>> handlers = new Dictionary<ushort, List<IMHandler>>();
  23. public void Awake()
  24. {
  25. this.Load();
  26. }
  27. public void Load()
  28. {
  29. this.handlers.Clear();
  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. IMHandler iMHandler = Activator.CreateInstance(type) as IMHandler;
  39. if (iMHandler == null)
  40. {
  41. Log.Error($"message handle {type.Name} 需要继承 IMHandler");
  42. continue;
  43. }
  44. Type messageType = iMHandler.GetMessageType();
  45. ushort opcode = this.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(messageType);
  46. if (opcode == 0)
  47. {
  48. Log.Error($"消息opcode为0: {messageType.Name}");
  49. continue;
  50. }
  51. this.RegisterHandler(opcode, iMHandler);
  52. }
  53. }
  54. public void RegisterHandler(ushort opcode, IMHandler handler)
  55. {
  56. if (!this.handlers.ContainsKey(opcode))
  57. {
  58. this.handlers.Add(opcode, new List<IMHandler>());
  59. }
  60. this.handlers[opcode].Add(handler);
  61. }
  62. public void Handle(Session session, MessageInfo messageInfo)
  63. {
  64. List<IMHandler> actions;
  65. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  66. {
  67. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  68. return;
  69. }
  70. foreach (IMHandler ev in actions)
  71. {
  72. try
  73. {
  74. ev.Handle(session, messageInfo.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. }