PingComponentSystem.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. TimerComponent.Instance?.Remove(ref self.Timer);
  30. }
  31. }
  32. private static async ETTask PingAsync(this PingComponent self)
  33. {
  34. Session session = self.GetParent<Session>();
  35. long instanceId = self.InstanceId;
  36. if (self.InstanceId != instanceId)
  37. {
  38. return;
  39. }
  40. long time1 = TimeHelper.ClientNow();
  41. try
  42. {
  43. G2C_Ping response = await session.Call(new C2G_Ping()) as G2C_Ping;
  44. if (self.InstanceId != instanceId)
  45. {
  46. return;
  47. }
  48. long time2 = TimeHelper.ClientNow();
  49. self.Ping = time2 - time1;
  50. TimeInfo.Instance.ServerMinusClientTime = response.Time + (time2 - time1) / 2 - time2;
  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. }