NetworkComponent.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using Common.Base;
  3. using Common.Network;
  4. using TNet;
  5. using UNet;
  6. namespace Model
  7. {
  8. public class NetworkComponent: Component<World>, IUpdate, IStart
  9. {
  10. private IService service;
  11. private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  12. {
  13. switch (protocol)
  14. {
  15. case NetworkProtocol.TCP:
  16. this.service = new TService(host, port);
  17. break;
  18. case NetworkProtocol.UDP:
  19. this.service = new UService(host, port);
  20. break;
  21. default:
  22. throw new ArgumentOutOfRangeException("protocol");
  23. }
  24. this.AcceptChannel();
  25. }
  26. public void Start()
  27. {
  28. this.Accept(World.Instance.Options.Host, World.Instance.Options.Port,
  29. 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<EventAttribute>>()
  60. .RunAsync(EventType.MessageAction, env);
  61. #pragma warning restore 4014
  62. }
  63. }
  64. }
  65. }