NetworkComponent.cs 1.4 KB

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