NetworkComponent.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Reflection;
  3. using Common.Base;
  4. using Common.Event;
  5. using Common.Network;
  6. using TNet;
  7. using UNet;
  8. namespace Model
  9. {
  10. public class NetworkComponent: Component<World>, IUpdate, IStart
  11. {
  12. private IService service;
  13. private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  14. {
  15. switch (protocol)
  16. {
  17. case NetworkProtocol.TCP:
  18. this.service = new TService(host, port);
  19. break;
  20. case NetworkProtocol.UDP:
  21. this.service = new UService(host, port);
  22. break;
  23. default:
  24. throw new ArgumentOutOfRangeException("protocol");
  25. }
  26. this.AcceptChannel();
  27. }
  28. public void Start()
  29. {
  30. this.Accept(World.Instance.Options.Host, World.Instance.Options.Port, World.Instance.Options.Protocol);
  31. }
  32. public void Update()
  33. {
  34. this.service.Update();
  35. }
  36. /// <summary>
  37. /// 接收连接
  38. /// </summary>
  39. private async void AcceptChannel()
  40. {
  41. while (true)
  42. {
  43. AChannel channel = await this.service.GetChannel();
  44. ProcessChannel(channel);
  45. }
  46. }
  47. /// <summary>
  48. /// 接收分发封包
  49. /// </summary>
  50. /// <param name="channel"></param>
  51. private static async void ProcessChannel(AChannel channel)
  52. {
  53. while (true)
  54. {
  55. byte[] message = await channel.RecvAsync();
  56. Env env = new Env();
  57. env[EnvKey.Channel] = channel;
  58. env[EnvKey.Message] = message;
  59. #pragma warning disable 4014
  60. World.Instance.GetComponent<EventComponent<ActionAttribute>>()
  61. .RunAsync(ActionType.MessageAction, env);
  62. #pragma warning restore 4014
  63. }
  64. }
  65. }
  66. }