Dispatcher.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using World;
  4. namespace Handler
  5. {
  6. public class Dispatcher : IDispatcher
  7. {
  8. private readonly Dictionary<short, IHandle> handlers = new Dictionary<short, IHandle>();
  9. public Dispatcher()
  10. {
  11. Type[] types = typeof (Dispatcher).Assembly.GetTypes();
  12. foreach (var type in types)
  13. {
  14. object[] attrs = type.GetCustomAttributes(typeof(HandlerAttribute), false);
  15. if (attrs.Length == 0)
  16. {
  17. continue;
  18. }
  19. var handler = (IHandle)Activator.CreateInstance(type);
  20. short opcode = ((HandlerAttribute)attrs[0]).Opcode;
  21. if (handlers.ContainsKey(opcode))
  22. {
  23. throw new Exception(string.Format("same opcode {0}", opcode));
  24. }
  25. handlers[opcode] = handler;
  26. }
  27. }
  28. public void Dispatch(MessageEnv messageEnv, short opcode, byte[] content)
  29. {
  30. IHandle handler = null;
  31. if (!handlers.TryGetValue(opcode, out handler))
  32. {
  33. throw new Exception(string.Format("not found handler opcode {0}", opcode));
  34. }
  35. handler.Handle(messageEnv, content);
  36. }
  37. }
  38. }