MessageDispatherComponent.cs 2.1 KB
Newer Older
T
tanghai 已提交
1 2 3 4 5
using System;
using System.Collections.Generic;

namespace Model
{
6 7 8 9 10 11 12 13 14 15 16 17 18 19
	[ObjectEvent]
	public class MessageDispatherComponentEvent : ObjectEvent<MessageDispatherComponent>, IAwake<AppType>, ILoad
	{
		public void Awake(AppType appType)
		{
			this.Get().Awake(appType);
		}

		public void Load()
		{
			this.Get().Load();
		}
	}

T
tanghai 已提交
20 21 22 23 24 25
	/// <summary>
	/// 消息分发组件
	/// </summary>
	public class MessageDispatherComponent : Component
	{
		private AppType AppType;
26
		private Dictionary<Type, List<IMHandler>> handlers;
T
tanghai 已提交
27

28
		public void Awake(AppType appType)
T
tanghai 已提交
29 30 31 32 33
		{
			this.AppType = appType;
			this.Load();
		}

34
		public void Load()
T
tanghai 已提交
35
		{
36
			this.handlers = new Dictionary<Type, List<IMHandler>>();
37
			
T
tanghai 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
			Type[] types = DllHelper.GetMonoTypes();
			foreach (Type type in types)
			{
				object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
				if (attrs.Length == 0)
				{
					continue;
				}

				MessageHandlerAttribute messageHandlerAttribute = (MessageHandlerAttribute)attrs[0];
				if (!messageHandlerAttribute.Type.Is(this.AppType))
				{
					continue;
				}

				object obj = Activator.CreateInstance(type);

				IMHandler imHandler = obj as IMHandler;
				if (imHandler == null)
				{
					throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
				}

				Type messageType = imHandler.GetMessageType();
62
				if (!this.handlers.TryGetValue(messageType, out List<IMHandler> list))
T
tanghai 已提交
63 64
				{
					list = new List<IMHandler>();
65
					this.handlers.Add(messageType, list);
T
tanghai 已提交
66 67 68 69 70
				}
				list.Add(imHandler);
			}
		}

71
		public void Handle(Session session, AMessage message)
T
tanghai 已提交
72
		{
73
			if (!this.handlers.TryGetValue(message.GetType(), out List<IMHandler> actions))
T
tanghai 已提交
74
			{
75
				Log.Error($"消息 {message.GetType().FullName} 没有处理");
T
tanghai 已提交
76 77
				return;
			}
78
			
T
tanghai 已提交
79 80 81 82
			foreach (IMHandler ev in actions)
			{
				try
				{
83
					ev.Handle(session, message);
T
tanghai 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
				}
				catch (Exception e)
				{
					Log.Error(e.ToString());
				}
			}
		}

		public override void Dispose()
		{
			if (this.Id == 0)
			{
				return;
			}

			base.Dispose();
		}
	}
}