MessageComponent.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 = (Opcode) Enum.Parse(typeof (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 void RegisterAsync<T, R>(Func<T, Task<R>> func)
  53. {
  54. Opcode opcode = (Opcode)Enum.Parse(typeof(Opcode), typeof(T).Name);
  55. eventsAsync.Add(opcode, async messageBytes =>
  56. {
  57. T t = MongoHelper.FromBson<T>(messageBytes, 6);
  58. R r = await func(t);
  59. return MongoHelper.ToBson(r);
  60. });
  61. }
  62. public async Task<byte[]> RunAsync(Opcode opcode, byte[] messageBytes)
  63. {
  64. Func<byte[], byte[]> func = null;
  65. if (this.events.TryGetValue(opcode, out func))
  66. {
  67. return func(messageBytes);
  68. }
  69. Func<byte[], Task<byte[]>> funcAsync = null;
  70. if (this.eventsAsync.TryGetValue(opcode, out funcAsync))
  71. {
  72. return await funcAsync(messageBytes);
  73. }
  74. throw new GameException(string.Format("not found opcode handler: {0}", opcode));
  75. }
  76. }
  77. }