PingComponentSystem.cs 2.0 KB

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