using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Common.Base; using Common.Helper; namespace Model { public class MessageComponent: Component, IAssemblyLoader { private Dictionary> events; private Dictionary>> eventsAsync; public void Load(Assembly assembly) { this.events = new Dictionary>(); this.eventsAsync = new Dictionary>>(); ServerType serverType = World.Instance.Options.ServerType; Type[] types = assembly.GetTypes(); foreach (Type t in types) { object[] attrs = t.GetCustomAttributes(typeof (MessageAttribute), false); if (attrs.Length == 0) { continue; } MessageAttribute messageAttribute = (MessageAttribute)attrs[0]; if (!messageAttribute.Contains(serverType)) { continue; } object obj = Activator.CreateInstance(t); IRegister iRegister = obj as IRegister; if (iRegister != null) { iRegister.Register(); } throw new Exception( string.Format("message handler not inherit IRegister interface: {0}", obj.GetType().FullName)); } } public void Register(Func func) { Opcode opcode = EnumHelper.FromString(typeof (T).Name); events.Add(opcode, messageBytes => { T t = MongoHelper.FromBson(messageBytes, 6); R k = func(t); return MongoHelper.ToBson(k); }); } public async Task RunAsync(Opcode opcode, byte[] messageBytes) { Func func = null; if (this.events.TryGetValue(opcode, out func)) { return func(messageBytes); } Func> funcAsync = null; if (this.eventsAsync.TryGetValue(opcode, out funcAsync)) { return await funcAsync(messageBytes); } throw new GameException(string.Format("not found opcode handler: {0}", opcode)); } } }