PingComponentSystem.cs 2.1 KB

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