MessageDispatcherComponent.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. 
  2. namespace KYFramework.Network
  3. {
  4. [ObjectSystem]
  5. public class MessageDispatcherComponentAwakeSystem : AwakeSystem<MessageDispatcherComponent>
  6. {
  7. public override void Awake(MessageDispatcherComponent t)
  8. {
  9. t.Awake();
  10. }
  11. }
  12. [ObjectSystem]
  13. public class MessageDispatcherComponentLoadSystem : LoadSystem<MessageDispatcherComponent>
  14. {
  15. public override void Load(MessageDispatcherComponent self)
  16. {
  17. self.Load();
  18. }
  19. }
  20. /// <summary>
  21. /// 消息分发组件
  22. /// </summary>
  23. public class MessageDispatcherComponent : Component
  24. {
  25. private readonly Dictionary<ushort, List<IMHandler>> handlers = new Dictionary<ushort, List<IMHandler>>();
  26. public void Awake()
  27. {
  28. this.Load();
  29. Log.Info("消息分发组件初始化完毕!");
  30. }
  31. public void Load()
  32. {
  33. this.handlers.Clear();
  34. List<Type> types = Game.EventSystem.GetTypes(typeof(MessageHandlerAttribute));
  35. foreach (Type type in types)
  36. {
  37. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  38. if (attrs.Length == 0)
  39. {
  40. continue;
  41. }
  42. IMHandler iMHandler = Activator.CreateInstance(type) as IMHandler;
  43. if (iMHandler == null)
  44. {
  45. Log.Error($"message handle {type.Name} 需要继承 IMHandler");
  46. continue;
  47. }
  48. Type messageType = iMHandler.GetMessageType();
  49. ushort opcode = this.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(messageType);
  50. if (opcode == 0)
  51. {
  52. Log.Error($"消息opcode为0: {messageType.Name}");
  53. continue;
  54. }
  55. this.RegisterHandler(opcode, iMHandler);
  56. }
  57. }
  58. public void RegisterHandler(ushort opcode, IMHandler handler)
  59. {
  60. if (!this.handlers.ContainsKey(opcode))
  61. {
  62. this.handlers.Add(opcode, new List<IMHandler>());
  63. }
  64. this.handlers[opcode].Add(handler);
  65. }
  66. public void Handle(Session session, MessageInfo messageInfo)
  67. {
  68. List<IMHandler> actions;
  69. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  70. {
  71. Log.Error($"消息没有处理: {messageInfo.Opcode} {JsonHelper.ToJson(messageInfo.Message)}");
  72. return;
  73. }
  74. foreach (IMHandler ev in actions)
  75. {
  76. try
  77. {
  78. ev.Handle(session, messageInfo.Message);
  79. }
  80. catch (Exception e)
  81. {
  82. Log.Error(e);
  83. }
  84. }
  85. }
  86. public override void Dispose()
  87. {
  88. if (this.IsDisposed)
  89. {
  90. return;
  91. }
  92. base.Dispose();
  93. }
  94. }
  95. }