ServiceComponent.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using Common.Base;
  3. using Common.Event;
  4. using Network;
  5. using TNet;
  6. using UNet;
  7. namespace Model
  8. {
  9. public class ServiceComponent: Component<World>
  10. {
  11. private IService service;
  12. public void Run(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  13. {
  14. switch (protocol)
  15. {
  16. case NetworkProtocol.TCP:
  17. service = new TService("127.0.0.1", 8888);
  18. break;
  19. case NetworkProtocol.UDP:
  20. service = new UService("127.0.0.1", 8888);
  21. break;
  22. default:
  23. throw new ArgumentOutOfRangeException("protocol");
  24. }
  25. service.Add(AcceptChannel);
  26. service.Run();
  27. }
  28. /// <summary>
  29. /// 接收连接
  30. /// </summary>
  31. private async void AcceptChannel()
  32. {
  33. while (true)
  34. {
  35. IChannel channel = await service.GetChannel();
  36. ProcessChannel(channel);
  37. }
  38. }
  39. /// <summary>
  40. /// 接收分发封包
  41. /// </summary>
  42. /// <param name="channel"></param>
  43. private static async void ProcessChannel(IChannel channel)
  44. {
  45. while (true)
  46. {
  47. byte[] message = await channel.RecvAsync();
  48. Env env = new Env();
  49. env[EnvKey.Message] = message;
  50. int opcode = BitConverter.ToUInt16(message, 0);
  51. World.Instance.GetComponent<EventComponent<MessageAttribute>>().Run(opcode, env);
  52. }
  53. }
  54. }
  55. }