ActorMessageDispatherComponent.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using Base;
  4. namespace Model
  5. {
  6. [ObjectEvent]
  7. public class ActorMessageDispatherComponentEvent : ObjectEvent<ActorMessageDispatherComponent>, IAwake<AppType>, ILoad
  8. {
  9. public void Awake(AppType appType)
  10. {
  11. this.Get().Awake(appType);
  12. }
  13. public void Load()
  14. {
  15. this.Get().Load();
  16. }
  17. }
  18. /// <summary>
  19. /// Actor消息分发组件
  20. /// </summary>
  21. public class ActorMessageDispatherComponent : Component
  22. {
  23. private AppType AppType;
  24. private Dictionary<Type, IMActorHandler> handlers;
  25. public void Awake(AppType appType)
  26. {
  27. this.AppType = appType;
  28. this.Load();
  29. }
  30. public void Load()
  31. {
  32. this.handlers = new Dictionary<Type, IMActorHandler>();
  33. Type[] types = DllHelper.GetMonoTypes();
  34. foreach (Type type in types)
  35. {
  36. object[] attrs = type.GetCustomAttributes(typeof(ActorMessageHandlerAttribute), false);
  37. if (attrs.Length == 0)
  38. {
  39. continue;
  40. }
  41. ActorMessageHandlerAttribute messageHandlerAttribute = (ActorMessageHandlerAttribute)attrs[0];
  42. if (!messageHandlerAttribute.Type.Is(this.AppType))
  43. {
  44. continue;
  45. }
  46. object obj = Activator.CreateInstance(type);
  47. IMActorHandler imHandler = obj as IMActorHandler;
  48. if (imHandler == null)
  49. {
  50. throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
  51. }
  52. Type messageType = imHandler.GetMessageType();
  53. handlers.Add(messageType, imHandler);
  54. }
  55. }
  56. public void Handle(Session session, MessageInfo messageInfo)
  57. {
  58. if (!this.handlers.TryGetValue(messageInfo.Message.GetType(), out IMActorHandler handler))
  59. {
  60. Log.Error($"not found message handler: {messageInfo.Message.GetType()}");
  61. return;
  62. }
  63. Entity entity = this.GetComponent<ActorManagerComponent>().Get(((AActorMessage)messageInfo.Message).Id);
  64. handler.Handle(session, entity, messageInfo);
  65. }
  66. public override void Dispose()
  67. {
  68. if (this.Id == 0)
  69. {
  70. return;
  71. }
  72. base.Dispose();
  73. }
  74. }
  75. }