MessageComponent.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. iRegister?.Register();
  34. throw new Exception($"message handler not inherit IRegister interface: {obj.GetType().FullName}");
  35. }
  36. }
  37. public void Register<T, R>(Func<T, R> func)
  38. {
  39. Opcode opcode = EnumHelper.FromString<Opcode>(typeof (T).Name);
  40. events.Add(opcode, messageBytes =>
  41. {
  42. T t = MongoHelper.FromBson<T>(messageBytes, 6);
  43. R k = func(t);
  44. return MongoHelper.ToBson(k);
  45. });
  46. }
  47. public async Task<byte[]> RunAsync(Opcode opcode, byte[] messageBytes)
  48. {
  49. Func<byte[], byte[]> func = null;
  50. if (this.events.TryGetValue(opcode, out func))
  51. {
  52. return func(messageBytes);
  53. }
  54. Func<byte[], Task<byte[]>> funcAsync = null;
  55. if (this.eventsAsync.TryGetValue(opcode, out funcAsync))
  56. {
  57. return await funcAsync(messageBytes);
  58. }
  59. throw new GameException($"not found opcode handler: {opcode}");
  60. }
  61. }
  62. }