NetworkComponent.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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>, IUpdate, IStart
  10. {
  11. private IService service;
  12. private void Accept(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.AcceptChannel();
  26. }
  27. public void Start()
  28. {
  29. this.Accept(World.Instance.Options.Host, World.Instance.Options.Port, World.Instance.Options.Protocol);
  30. }
  31. public void Update()
  32. {
  33. this.service.Update();
  34. }
  35. /// <summary>
  36. /// 接收连接
  37. /// </summary>
  38. private async void AcceptChannel()
  39. {
  40. while (true)
  41. {
  42. AChannel channel = await this.service.GetChannel();
  43. ProcessChannel(channel);
  44. }
  45. }
  46. /// <summary>
  47. /// 接收分发封包
  48. /// </summary>
  49. /// <param name="channel"></param>
  50. private static async void ProcessChannel(AChannel channel)
  51. {
  52. while (true)
  53. {
  54. byte[] message = await channel.RecvAsync();
  55. Env env = new Env();
  56. env[EnvKey.Channel] = channel;
  57. env[EnvKey.Message] = message;
  58. #pragma warning disable 4014
  59. World.Instance.GetComponent<EventComponent<ActionAttribute>>()
  60. .RunAsync(ActionType.MessageAction, env);
  61. #pragma warning restore 4014
  62. }
  63. }
  64. }
  65. }