MessageComponent.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Threading.Tasks;
  5. using Common.Base;
  6. using Common.Helper;
  7. namespace Model
  8. {
  9. public class MessageComponent: Component<World>, IAssemblyLoader
  10. {
  11. private Dictionary<Opcode, Func<byte[], byte[]>> events;
  12. private Dictionary<Opcode, Func<byte[], Task<byte[]>>> eventsAsync;
  13. public void Load(Assembly assembly)
  14. {
  15. this.events = new Dictionary<Opcode, Func<byte[], byte[]>>();
  16. this.eventsAsync = new Dictionary<Opcode, Func<byte[], Task<byte[]>>>();
  17. ServerType serverType = World.Instance.Options.ServerType;
  18. Type[] types = assembly.GetTypes();
  19. foreach (Type t in types)
  20. {
  21. object[] attrs = t.GetCustomAttributes(typeof (MessageAttribute), false);
  22. if (attrs.Length == 0)
  23. {
  24. continue;
  25. }
  26. MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
  27. if (!messageAttribute.Contains(serverType))
  28. {
  29. continue;
  30. }
  31. object obj = Activator.CreateInstance(t);
  32. IRegister iRegister = obj as IRegister;
  33. if (iRegister != null)
  34. {
  35. iRegister.Register();
  36. }
  37. throw new Exception(
  38. string.Format("message handler not inherit IRegister interface: {0}",
  39. obj.GetType().FullName));
  40. }
  41. }
  42. public void Register<T, R>(Func<T, R> func)
  43. {
  44. Opcode opcode = EnumHelper.FromString<Opcode>(typeof (T).Name);
  45. events.Add(opcode, messageBytes =>
  46. {
  47. T t = MongoHelper.FromBson<T>(messageBytes, 6);
  48. R k = func(t);
  49. return MongoHelper.ToBson(k);
  50. });
  51. }
  52. public async Task<byte[]> RunAsync(Opcode opcode, byte[] messageBytes)
  53. {
  54. Func<byte[], byte[]> func = null;
  55. if (this.events.TryGetValue(opcode, out func))
  56. {
  57. return func(messageBytes);
  58. }
  59. Func<byte[], Task<byte[]>> funcAsync = null;
  60. if (this.eventsAsync.TryGetValue(opcode, out funcAsync))
  61. {
  62. return await funcAsync(messageBytes);
  63. }
  64. throw new GameException(string.Format("not found opcode handler: {0}", opcode));
  65. }
  66. }
  67. }