PingComponentSystem.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. namespace ET.Client
  3. {
  4. [ObjectSystem]
  5. public class PingComponentAwakeSystem: AwakeSystem<PingComponent>
  6. {
  7. protected override void Awake(PingComponent self)
  8. {
  9. PingAsync(self).Coroutine();
  10. }
  11. private static async ETTask PingAsync(PingComponent self)
  12. {
  13. Session session = self.GetParent<Session>();
  14. long instanceId = self.InstanceId;
  15. while (true)
  16. {
  17. if (self.InstanceId != instanceId)
  18. {
  19. return;
  20. }
  21. long time1 = TimeHelper.ClientNow();
  22. try
  23. {
  24. G2C_Ping response = await session.Call(new C2G_Ping()) as G2C_Ping;
  25. if (self.InstanceId != instanceId)
  26. {
  27. return;
  28. }
  29. long time2 = TimeHelper.ClientNow();
  30. self.Ping = time2 - time1;
  31. TimeInfo.Instance.ServerMinusClientTime = response.Time + (time2 - time1) / 2 - time2;
  32. await TimerComponent.Instance.WaitAsync(2000);
  33. }
  34. catch (RpcException e)
  35. {
  36. // session断开导致ping rpc报错,记录一下即可,不需要打成error
  37. Log.Info($"ping error: {self.Id} {e.Error}");
  38. return;
  39. }
  40. catch (Exception e)
  41. {
  42. Log.Error($"ping error: \n{e}");
  43. }
  44. }
  45. }
  46. }
  47. [ObjectSystem]
  48. public class PingComponentDestroySystem: DestroySystem<PingComponent>
  49. {
  50. protected override void Destroy(PingComponent self)
  51. {
  52. self.Ping = default;
  53. }
  54. }
  55. }