MessageDispatherComponent.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using Model;
  4. namespace Hotfix
  5. {
  6. [ObjectSystem]
  7. public class MessageDispatherComponentSystem : ObjectSystem<MessageDispatherComponent>, IAwake, ILoad
  8. {
  9. public void Awake()
  10. {
  11. this.Get().Awake();
  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 Dictionary<ushort, List<IMHandler>> handlers;
  24. public void Awake()
  25. {
  26. this.Load();
  27. }
  28. public void Load()
  29. {
  30. this.handlers = new Dictionary<ushort, List<IMHandler>>();
  31. Type[] types = DllHelper.GetHotfixTypes();
  32. foreach (Type type in types)
  33. {
  34. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  35. if (attrs.Length == 0)
  36. {
  37. continue;
  38. }
  39. MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
  40. IMHandler iMHandler = (IMHandler)Activator.CreateInstance(type);
  41. if (!this.handlers.ContainsKey(messageHandlerAttribute.Opcode))
  42. {
  43. this.handlers.Add(messageHandlerAttribute.Opcode, new List<IMHandler>());
  44. }
  45. this.handlers[messageHandlerAttribute.Opcode].Add(iMHandler);
  46. }
  47. }
  48. public void Handle(Session session, ushort opcode, IMessage message)
  49. {
  50. if (!this.handlers.TryGetValue(opcode, out List<IMHandler> actions))
  51. {
  52. Log.Error($"消息 {message.GetType().FullName} 没有处理");
  53. return;
  54. }
  55. foreach (IMHandler ev in actions)
  56. {
  57. try
  58. {
  59. ev.Handle(null, 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. }