MessageDispatherComponent.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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<IInstanceMethod>> handlers;
  12. private DoubleMap<ushort, Type> opcodeTypes = new DoubleMap<ushort, Type>();
  13. public void Awake()
  14. {
  15. this.Load();
  16. }
  17. public void Load()
  18. {
  19. this.handlers = new Dictionary<ushort, List<IInstanceMethod>>();
  20. this.opcodeTypes = new DoubleMap<ushort, Type>();
  21. Type[] monoTypes = DllHelper.GetMonoTypes();
  22. foreach (Type monoType in monoTypes)
  23. {
  24. object[] attrs = monoType.GetCustomAttributes(typeof(MessageAttribute), false);
  25. if (attrs.Length == 0)
  26. {
  27. continue;
  28. }
  29. MessageAttribute messageAttribute = attrs[0] as MessageAttribute;
  30. if (messageAttribute == null)
  31. {
  32. continue;
  33. }
  34. this.opcodeTypes.Add(messageAttribute.Opcode, monoType);
  35. }
  36. Type[] types = DllHelper.GetMonoTypes();
  37. foreach (Type type in types)
  38. {
  39. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  40. if (attrs.Length == 0)
  41. {
  42. continue;
  43. }
  44. MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
  45. IInstanceMethod method = new ILInstanceMethod(type, "Handle");
  46. if (!this.handlers.ContainsKey(messageHandlerAttribute.Opcode))
  47. {
  48. this.handlers.Add(messageHandlerAttribute.Opcode, new List<IInstanceMethod>());
  49. }
  50. this.handlers[messageHandlerAttribute.Opcode].Add(method);
  51. }
  52. }
  53. public ushort GetOpcode(Type type)
  54. {
  55. return this.opcodeTypes.GetKeyByValue(type);
  56. }
  57. public void Handle(Session session, MessageInfo messageInfo)
  58. {
  59. List<IInstanceMethod> actions;
  60. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  61. {
  62. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  63. return;
  64. }
  65. Type messageType = this.opcodeTypes.GetValueByKey(messageInfo.Opcode);
  66. object message = JsonHelper.FromJson(messageType, messageInfo.MessageBytes, messageInfo.Offset, messageInfo.Count);
  67. messageInfo.Message = message;
  68. foreach (IInstanceMethod ev in actions)
  69. {
  70. try
  71. {
  72. ev.Run(session, messageInfo.Message);
  73. }
  74. catch (Exception e)
  75. {
  76. Log.Error(e.ToString());
  77. }
  78. }
  79. }
  80. public override void Dispose()
  81. {
  82. if (this.Id == 0)
  83. {
  84. return;
  85. }
  86. base.Dispose();
  87. }
  88. }
  89. }