GateNetworkComponent.cs 1.6 KB

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