MessageDispatherComponent.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using Model;
  4. namespace Hotfix
  5. {
  6. [ObjectEvent]
  7. public class MessageDispatherComponentEvent : ObjectEvent<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, IAwake, ILoad
  22. {
  23. private Dictionary<ushort, List<IMHandler>> handlers;
  24. public void Awake()
  25. {
  26. this.Load();
  27. }
  28. public void Load()
  29. {
  30. 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(MessageInfo messageInfo)
  49. {
  50. List<IMHandler> actions;
  51. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  52. {
  53. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  54. return;
  55. }
  56. foreach (IMHandler ev in actions)
  57. {
  58. try
  59. {
  60. ev.Handle(messageInfo.Message);
  61. }
  62. catch (Exception e)
  63. {
  64. Log.Error(e.ToStr());
  65. }
  66. }
  67. }
  68. public override void Dispose()
  69. {
  70. if (this.Id == 0)
  71. {
  72. return;
  73. }
  74. base.Dispose();
  75. }
  76. }
  77. }