MessageDispatherComponent.cs 1.5 KB

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