RouterAddressComponentSystem.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. namespace ET.Client
  6. {
  7. [FriendOf(typeof(RouterAddressComponent))]
  8. public static class RouterAddressComponentSystem
  9. {
  10. public class RouterAddressComponentAwakeSystem: AwakeSystem<RouterAddressComponent, string, int>
  11. {
  12. protected override void Awake(RouterAddressComponent self, string address, int port)
  13. {
  14. self.RouterManagerHost = address;
  15. self.RouterManagerPort = port;
  16. }
  17. }
  18. public static async ETTask Init(this RouterAddressComponent self)
  19. {
  20. self.RouterManagerIPAddress = NetworkHelper.GetHostAddress(self.RouterManagerHost);
  21. await self.GetAllRouter();
  22. }
  23. private static async ETTask GetAllRouter(this RouterAddressComponent self)
  24. {
  25. string url = $"http://{self.RouterManagerHost}:{self.RouterManagerPort}/get_router?v={RandomGenerator.RandUInt32()}";
  26. Log.Debug($"start get router info: {url}");
  27. string routerInfo = await HttpClientHelper.Get(url);
  28. Log.Debug($"recv router info: {routerInfo}");
  29. HttpGetRouterResponse httpGetRouterResponse = JsonHelper.FromJson<HttpGetRouterResponse>(routerInfo);
  30. self.Info = httpGetRouterResponse;
  31. // 打乱顺序
  32. RandomGenerator.BreakRank(self.Info.Routers);
  33. //self.WaitTenMinGetAllRouter().Coroutine();
  34. }
  35. // 等10分钟再获取一次
  36. public static async ETTask WaitTenMinGetAllRouter(this RouterAddressComponent self)
  37. {
  38. await TimerComponent.Instance.WaitAsync(5 * 60 * 1000);
  39. if (self.IsDisposed)
  40. {
  41. return;
  42. }
  43. await self.GetAllRouter();
  44. }
  45. public static IPEndPoint GetAddress(this RouterAddressComponent self)
  46. {
  47. if (self.Info.Routers.Count == 0)
  48. {
  49. return null;
  50. }
  51. string address = self.Info.Routers[self.RouterIndex++ % self.Info.Routers.Count];
  52. string[] ss = address.Split(':');
  53. IPAddress ipAddress = IPAddress.Parse(ss[0]);
  54. if (self.RouterManagerIPAddress.AddressFamily == AddressFamily.InterNetworkV6)
  55. {
  56. ipAddress = ipAddress.MapToIPv6();
  57. }
  58. return new IPEndPoint(ipAddress, int.Parse(ss[1]));
  59. }
  60. public static IPEndPoint GetRealmAddress(this RouterAddressComponent self, string account)
  61. {
  62. int v = account.Mode(self.Info.Realms.Count);
  63. string address = self.Info.Realms[v];
  64. string[] ss = address.Split(':');
  65. IPAddress ipAddress = IPAddress.Parse(ss[0]);
  66. //if (self.IPAddress.AddressFamily == AddressFamily.InterNetworkV6)
  67. //{
  68. // ipAddress = ipAddress.MapToIPv6();
  69. //}
  70. return new IPEndPoint(ipAddress, int.Parse(ss[1]));
  71. }
  72. }
  73. }