MessageDispatherComponent.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using Base;
  4. namespace Model
  5. {
  6. /// <summary>
  7. /// 消息分发组件
  8. /// </summary>
  9. [EntityEvent(EntityEventId.MessageDispatherComponent)]
  10. public class MessageDispatherComponent: Component
  11. {
  12. private AppType AppType;
  13. private Dictionary<ushort, List<IInstanceMethod>> handlers;
  14. private DoubleMap<ushort, Type> opcodeTypes = new DoubleMap<ushort, Type>();
  15. private void Awake(AppType appType)
  16. {
  17. this.AppType = appType;
  18. this.Load();
  19. }
  20. private void Load()
  21. {
  22. this.handlers = new Dictionary<ushort, List<IInstanceMethod>>();
  23. this.opcodeTypes = new DoubleMap<ushort, Type>();
  24. Type[] monoTypes = DllHelper.GetMonoTypes();
  25. foreach (Type monoType in monoTypes)
  26. {
  27. object[] attrs = monoType.GetCustomAttributes(typeof(MessageAttribute), false);
  28. if (attrs.Length == 0)
  29. {
  30. continue;
  31. }
  32. MessageAttribute messageAttribute = attrs[0] as MessageAttribute;
  33. if (messageAttribute == null)
  34. {
  35. continue;
  36. }
  37. this.opcodeTypes.Add(messageAttribute.Opcode, monoType);
  38. }
  39. Type[] ilTypes = DllHelper.GetHotfixTypes();
  40. foreach (Type type in ilTypes)
  41. {
  42. object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
  43. MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
  44. IInstanceMethod method = new ILInstanceMethod(type, "Handle");
  45. if (!this.handlers.ContainsKey(messageHandlerAttribute.Opcode))
  46. {
  47. this.handlers.Add(messageHandlerAttribute.Opcode, new List<IInstanceMethod>());
  48. }
  49. this.handlers[messageHandlerAttribute.Opcode].Add(method);
  50. }
  51. }
  52. public ushort GetOpcode(Type type)
  53. {
  54. return this.opcodeTypes.GetKeyByValue(type);
  55. }
  56. public void Handle(Session session, MessageInfo messageInfo)
  57. {
  58. List<IInstanceMethod> actions;
  59. if (!this.handlers.TryGetValue(messageInfo.Opcode, out actions))
  60. {
  61. Log.Error($"消息 {messageInfo.Opcode} 没有处理");
  62. return;
  63. }
  64. Type messageType = this.opcodeTypes.GetValueByKey(messageInfo.Opcode);
  65. object message = MongoHelper.FromBson(messageType, messageInfo.MessageBytes, messageInfo.Offset, messageInfo.Count);
  66. messageInfo.Message = message;
  67. foreach (IInstanceMethod ev in actions)
  68. {
  69. try
  70. {
  71. ev.Run(session, messageInfo);
  72. }
  73. catch (Exception e)
  74. {
  75. Log.Error(e.ToString());
  76. }
  77. }
  78. }
  79. public override void Dispose()
  80. {
  81. if (this.Id == 0)
  82. {
  83. return;
  84. }
  85. base.Dispose();
  86. }
  87. }
  88. }