PingComponentSystem.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. namespace ET.Client
  3. {
  4. [EntitySystemOf(typeof(PingComponent))]
  5. public static partial class PingComponentSystem
  6. {
  7. [EntitySystem]
  8. private static void Awake(this PingComponent self)
  9. {
  10. self.PingAsync().NoContext();
  11. }
  12. [EntitySystem]
  13. private static void Destroy(this PingComponent self)
  14. {
  15. self.Ping = default;
  16. }
  17. private static async ETTask PingAsync(this PingComponent self)
  18. {
  19. Session session = self.GetParent<Session>();
  20. long instanceId = self.InstanceId;
  21. Fiber fiber = self.Fiber();
  22. while (true)
  23. {
  24. try
  25. {
  26. await fiber.Root.GetComponent<TimerComponent>().WaitAsync(2000);
  27. if (self.InstanceId != instanceId)
  28. {
  29. return;
  30. }
  31. long time1 = TimeInfo.Instance.ClientNow();
  32. // C2G_Ping不需要调用dispose,Call中会判断,如果用了对象池会自动回收
  33. C2G_Ping c2GPing = C2G_Ping.Create(true);
  34. // 这里response要用using才能回收到池,默认不回收
  35. using G2C_Ping response = await session.Call(c2GPing) as G2C_Ping;
  36. if (self.InstanceId != instanceId)
  37. {
  38. return;
  39. }
  40. long time2 = TimeInfo.Instance.ClientNow();
  41. self.Ping = time2 - time1;
  42. TimeInfo.Instance.ServerMinusClientTime = response.Time + (time2 - time1) / 2 - time2;
  43. }
  44. catch (RpcException e)
  45. {
  46. // session断开导致ping rpc报错,记录一下即可,不需要打成error
  47. Log.Debug($"session disconnect, ping error: {self.Id} {e.Error}");
  48. return;
  49. }
  50. catch (Exception e)
  51. {
  52. Log.Debug($"ping error: \n{e}");
  53. }
  54. }
  55. }
  56. }
  57. }