MessageDispatherComponent.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using Model;
  4. namespace Hotfix
  5. {
  6. /// <summary>
  7. /// 消息分发组件
  8. /// </summary>
  9. [ObjectEvent((int)EntityEventId.MessageDispatherComponent)]
  10. public class MessageDispatherComponent: Component, IAwake, ILoad
  11. {
  12. private Dictionary<ushort, List<IMHandler>> handlers;
  13. public void Awake()
  14. {
  15. this.Load();
  16. }
  17. public void Load()
  18. {
  19. handlers = new Dictionary<ushort, List<IMHandler>>();
  20. Type[] types = DllHelper.GetHotfixTypes();
  21. foreach (Type type in types)
  22. {
  23. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  24. if (attrs.Length == 0)
  25. {
  26. continue;
  27. }
  28. MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
  29. IMHandler iMHandler = (IMHandler)Activator.CreateInstance(type);
  30. if (!this.handlers.ContainsKey(messageHandlerAttribute.Opcode))
  31. {
  32. this.handlers.Add(messageHandlerAttribute.Opcode, new List<IMHandler>());
  33. }
  34. this.handlers[messageHandlerAttribute.Opcode].Add(iMHandler);
  35. }
  36. }
  37. public void Handle(MessageInfo messageInfo)
  38. {
  39. List<IMHandler> actions;
  40. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  41. {
  42. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  43. return;
  44. }
  45. foreach (IMHandler ev in actions)
  46. {
  47. try
  48. {
  49. ev.Handle(messageInfo.Message);
  50. }
  51. catch (Exception e)
  52. {
  53. Log.Error(e.ToStr());
  54. }
  55. }
  56. }
  57. public override void Dispose()
  58. {
  59. if (this.Id == 0)
  60. {
  61. return;
  62. }
  63. base.Dispose();
  64. }
  65. }
  66. }