LogicEntry.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Component;
  5. using Helper;
  6. using Logic;
  7. namespace World
  8. {
  9. public class LogicEntry : ILogicEntry
  10. {
  11. private static readonly LogicEntry instance = new LogicEntry();
  12. private Dictionary<short, IHandler> handlers;
  13. public static LogicEntry Instance
  14. {
  15. get
  16. {
  17. return instance;
  18. }
  19. }
  20. public LogicEntry()
  21. {
  22. this.Load();
  23. }
  24. public void Load()
  25. {
  26. this.handlers = new Dictionary<short, IHandler>();
  27. string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logic.dll");
  28. if (!File.Exists(dllPath))
  29. {
  30. throw new Exception(string.Format("not found logic dll, path: {0}", dllPath));
  31. }
  32. var assembly = LoaderHelper.Load(dllPath);
  33. Type[] types = assembly.GetTypes();
  34. foreach (var type in types)
  35. {
  36. object[] attrs = type.GetCustomAttributes(typeof(HandlerAttribute), false);
  37. if (attrs.Length == 0)
  38. {
  39. continue;
  40. }
  41. var handler = (IHandler)Activator.CreateInstance(type);
  42. short opcode = ((HandlerAttribute)attrs[0]).Opcode;
  43. if (this.handlers.ContainsKey(opcode))
  44. {
  45. throw new Exception(string.Format(
  46. "same opcode, opcode: {0}, name: {1}", opcode, type.Name));
  47. }
  48. this.handlers[opcode] = handler;
  49. }
  50. }
  51. public void Reload()
  52. {
  53. this.Load();
  54. }
  55. public void Enter(MessageEnv messageEnv, short opcode, byte[] content)
  56. {
  57. IHandler handler = null;
  58. if (!handlers.TryGetValue(opcode, out handler))
  59. {
  60. throw new Exception(string.Format("not found handler opcode {0}", opcode));
  61. }
  62. handler.Handle(messageEnv, content);
  63. }
  64. }
  65. }