ServiceComponent.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. this.service = new TService(host, port);
  18. break;
  19. case NetworkProtocol.UDP:
  20. this.service = new UService(host, port);
  21. break;
  22. default:
  23. throw new ArgumentOutOfRangeException("protocol");
  24. }
  25. this.service.Add(this.AcceptChannel);
  26. this.service.Run();
  27. }
  28. /// <summary>
  29. /// 接收连接
  30. /// </summary>
  31. private async void AcceptChannel()
  32. {
  33. while (true)
  34. {
  35. AChannel channel = await this.service.GetChannel();
  36. ProcessChannel(channel);
  37. }
  38. }
  39. /// <summary>
  40. /// 接收分发封包
  41. /// </summary>
  42. /// <param name="channel"></param>
  43. private static async void ProcessChannel(AChannel channel)
  44. {
  45. while (true)
  46. {
  47. byte[] message = await channel.RecvAsync();
  48. Env env = new Env();
  49. env[EnvKey.Channel] = channel;
  50. env[EnvKey.Message] = message;
  51. await World.Instance.GetComponent<EventComponent<ActionAttribute>>()
  52. .Run(ActionType.MessageAction, env);
  53. }
  54. }
  55. }
  56. }