NetworkComponent.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using Common.Base;
  3. using Common.Event;
  4. using Common.Network;
  5. using TNet;
  6. using UNet;
  7. namespace Model
  8. {
  9. public class NetworkComponent: 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. #pragma warning disable 4014
  52. World.Instance.GetComponent<EventComponent<ActionAttribute>>()
  53. .RunAsync(ActionType.MessageAction, env);
  54. #pragma warning restore 4014
  55. }
  56. }
  57. }
  58. }