ConnectionHandler.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // ----------------------------------------------------------------------------
  2. // <copyright file="ConnectionHandler.cs" company="Exit Games GmbH">
  3. // Loadbalancing Framework for Photon - Copyright (C) 2018 Exit Games GmbH
  4. // </copyright>
  5. // <summary>
  6. // If the game logic does not call Service() for whatever reason, this keeps the connection.
  7. // </summary>
  8. // <author>developer@photonengine.com</author>
  9. // ----------------------------------------------------------------------------
  10. #if UNITY_4_7 || UNITY_5 || UNITY_5_3_OR_NEWER
  11. #define SUPPORTED_UNITY
  12. #endif
  13. namespace Photon.Realtime
  14. {
  15. using System;
  16. using System.Diagnostics;
  17. using System.Text;
  18. using SupportClass = ExitGames.Client.Photon.SupportClass;
  19. #if SUPPORTED_UNITY
  20. using UnityEngine;
  21. #endif
  22. #if SUPPORTED_UNITY
  23. public class ConnectionHandler : MonoBehaviour
  24. #else
  25. public class ConnectionHandler
  26. #endif
  27. {
  28. /// <summary>
  29. /// Photon client to log information and statistics from.
  30. /// </summary>
  31. public LoadBalancingClient Client { get; set; }
  32. /// <summary>Option to let the fallback thread call Disconnect after the KeepAliveInBackground time. Default: false.</summary>
  33. /// <remarks>
  34. /// If set to true, the thread will disconnect the client regularly, should the client not call SendOutgoingCommands / Service.
  35. /// This may happen due to an app being in background (and not getting a lot of CPU time) or when loading assets.
  36. ///
  37. /// If false, a regular timeout time will have to pass (on top) to time out the client.
  38. /// </remarks>
  39. public bool DisconnectAfterKeepAlive = false;
  40. /// <summary>Defines for how long the Fallback Thread should keep the connection, before it may time out as usual.</summary>
  41. /// <remarks>We want to the Client to keep it's connection when an app is in the background (and doesn't call Update / Service Clients should not keep their connection indefinitely in the background, so after some milliseconds, the Fallback Thread should stop keeping it up.</remarks>
  42. public int KeepAliveInBackground = 60000;
  43. /// <summary>Counts how often the Fallback Thread called SendAcksOnly, which is purely of interest to monitor if the game logic called SendOutgoingCommands as intended.</summary>
  44. public int CountSendAcksOnly { get; private set; }
  45. /// <summary>True if a fallback thread is running. Will call the client's SendAcksOnly() method to keep the connection up.</summary>
  46. public bool FallbackThreadRunning
  47. {
  48. get { return this.fallbackThreadId < 255; }
  49. }
  50. /// <summary>Keeps the ConnectionHandler, even if a new scene gets loaded.</summary>
  51. public bool ApplyDontDestroyOnLoad = true;
  52. /// <summary>Indicates that the app is closing. Set in OnApplicationQuit().</summary>
  53. [NonSerialized]
  54. public static bool AppQuits;
  55. [NonSerialized]
  56. public static bool AppPause;
  57. [NonSerialized]
  58. public static bool AppPauseRecent;
  59. [NonSerialized]
  60. public static bool AppOutOfFocus;
  61. [NonSerialized]
  62. public static bool AppOutOfFocusRecent;
  63. private byte fallbackThreadId = 255;
  64. private bool didSendAcks;
  65. private readonly Stopwatch backgroundStopwatch = new Stopwatch();
  66. #if SUPPORTED_UNITY
  67. #if UNITY_2019_4_OR_NEWER
  68. /// <summary>
  69. /// Resets statics for Domain Reload
  70. /// </summary>
  71. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  72. static void StaticReset()
  73. {
  74. AppQuits = false;
  75. AppPause = false;
  76. AppPauseRecent = false;
  77. AppOutOfFocus = false;
  78. AppOutOfFocusRecent = false;
  79. }
  80. #endif
  81. /// <summary>Called by Unity when the application gets closed. The UnityEngine will also call OnDisable, which disconnects.</summary>
  82. public void OnApplicationQuit()
  83. {
  84. AppQuits = true;
  85. }
  86. /// <summary>Called by Unity when the application gets paused or resumed.</summary>
  87. public void OnApplicationPause(bool pause)
  88. {
  89. AppPause = pause;
  90. if (pause)
  91. {
  92. AppPauseRecent = true;
  93. this.CancelInvoke(nameof(this.ResetAppPauseRecent));
  94. }
  95. else
  96. {
  97. Invoke(nameof(this.ResetAppPauseRecent), 5f);
  98. }
  99. }
  100. private void ResetAppPauseRecent()
  101. {
  102. AppPauseRecent = false;
  103. }
  104. /// <summary>Called by Unity when the application changes focus.</summary>
  105. public void OnApplicationFocus(bool focus)
  106. {
  107. AppOutOfFocus = !focus;
  108. if (!focus)
  109. {
  110. AppOutOfFocusRecent = true;
  111. this.CancelInvoke(nameof(this.ResetAppOutOfFocusRecent));
  112. }
  113. else
  114. {
  115. this.Invoke(nameof(this.ResetAppOutOfFocusRecent), 5f);
  116. }
  117. }
  118. private void ResetAppOutOfFocusRecent()
  119. {
  120. AppOutOfFocusRecent = false;
  121. }
  122. /// <summary></summary>
  123. protected virtual void Awake()
  124. {
  125. if (this.ApplyDontDestroyOnLoad)
  126. {
  127. DontDestroyOnLoad(this.gameObject);
  128. }
  129. }
  130. /// <summary>Called by Unity when the application gets closed. Disconnects if OnApplicationQuit() was called before.</summary>
  131. protected virtual void OnDisable()
  132. {
  133. this.StopFallbackSendAckThread();
  134. if (AppQuits)
  135. {
  136. if (this.Client != null && this.Client.IsConnected)
  137. {
  138. this.Client.Disconnect(DisconnectCause.ApplicationQuit);
  139. this.Client.LoadBalancingPeer.StopThread();
  140. }
  141. SupportClass.StopAllBackgroundCalls();
  142. }
  143. }
  144. #endif
  145. /// <summary>
  146. /// When run in Unity, this returns Application.internetReachability != NetworkReachability.NotReachable.
  147. /// </summary>
  148. /// <returns>Application.internetReachability != NetworkReachability.NotReachable</returns>
  149. public static bool IsNetworkReachableUnity()
  150. {
  151. #if SUPPORTED_UNITY
  152. return Application.internetReachability != NetworkReachability.NotReachable;
  153. #else
  154. return true;
  155. #endif
  156. }
  157. public void StartFallbackSendAckThread()
  158. {
  159. #if !UNITY_WEBGL
  160. if (this.FallbackThreadRunning)
  161. {
  162. return;
  163. }
  164. #if UNITY_SWITCH
  165. this.fallbackThreadId = SupportClass.StartBackgroundCalls(this.RealtimeFallbackThread, 50); // as workaround, we don't name the Thread.
  166. #else
  167. this.fallbackThreadId = SupportClass.StartBackgroundCalls(this.RealtimeFallbackThread, 50, "RealtimeFallbackThread");
  168. #endif
  169. #endif
  170. }
  171. public void StopFallbackSendAckThread()
  172. {
  173. #if !UNITY_WEBGL
  174. if (!this.FallbackThreadRunning)
  175. {
  176. return;
  177. }
  178. SupportClass.StopBackgroundCalls(this.fallbackThreadId);
  179. this.fallbackThreadId = 255;
  180. #endif
  181. }
  182. /// <summary>A thread which runs independent from the Update() calls. Keeps connections online while loading or in background. See <see cref="KeepAliveInBackground"/>.</summary>
  183. public bool RealtimeFallbackThread()
  184. {
  185. if (this.Client != null)
  186. {
  187. if (!this.Client.IsConnected)
  188. {
  189. this.didSendAcks = false;
  190. return true;
  191. }
  192. if (this.Client.LoadBalancingPeer.ConnectionTime - this.Client.LoadBalancingPeer.LastSendOutgoingTime > 100)
  193. {
  194. if (!this.didSendAcks)
  195. {
  196. backgroundStopwatch.Reset();
  197. backgroundStopwatch.Start();
  198. }
  199. // check if the client should disconnect after some seconds in background
  200. if (backgroundStopwatch.ElapsedMilliseconds > this.KeepAliveInBackground)
  201. {
  202. if (this.DisconnectAfterKeepAlive)
  203. {
  204. this.Client.Disconnect();
  205. }
  206. return true;
  207. }
  208. this.didSendAcks = true;
  209. this.CountSendAcksOnly++;
  210. this.Client.LoadBalancingPeer.SendAcksOnly();
  211. }
  212. else
  213. {
  214. this.didSendAcks = false;
  215. }
  216. }
  217. return true;
  218. }
  219. }
  220. /// <summary>
  221. /// The SystemConnectionSummary (SBS) is useful to analyze low level connection issues in Unity. This requires a ConnectionHandler in the scene.
  222. /// </summary>
  223. /// <remarks>
  224. /// A LoadBalancingClient automatically creates a SystemConnectionSummary on these disconnect causes:
  225. /// DisconnectCause.ExceptionOnConnect, DisconnectCause.Exception, DisconnectCause.ServerTimeout and DisconnectCause.ClientTimeout.
  226. ///
  227. /// The SBS can then be turned into an integer (ToInt()) or string to debug the situation or use in analytics.
  228. /// Both, ToString and ToInt summarize the network-relevant conditions of the client at and before the connection fail, including the PhotonPeer.SocketErrorCode.
  229. ///
  230. /// Important: To correctly create the SBS instance, a ConnectionHandler component must be present and enabled in the
  231. /// Unity scene hierarchy. In best case, keep the ConnectionHandler on a GameObject which is flagged as
  232. /// DontDestroyOnLoad.
  233. /// </remarks>
  234. public class SystemConnectionSummary
  235. {
  236. // SystemConditionSummary v0 has 32 bits:
  237. // Version bits (4 bits)
  238. // UDP, TCP, WS, WSS (WebRTC potentially) (3 bits)
  239. // 1 bit empty
  240. //
  241. // AppQuits
  242. // AppPause
  243. // AppPauseRecent
  244. // AppOutOfFocus
  245. //
  246. // AppOutOfFocusRecent
  247. // NetworkReachability (Unity value)
  248. // ErrorCodeFits (ErrorCode > short.Max would be a problem)
  249. // WinSock (true) or BSD (false) Socket Error Codes
  250. //
  251. // Time since receive?
  252. // Times of send?!
  253. //
  254. // System/Platform -> should be in other analytic values (not this)
  255. public readonly byte Version = 0;
  256. public byte UsedProtocol;
  257. public bool AppQuits;
  258. public bool AppPause;
  259. public bool AppPauseRecent;
  260. public bool AppOutOfFocus;
  261. public bool AppOutOfFocusRecent;
  262. public bool NetworkReachable;
  263. public bool ErrorCodeFits;
  264. public bool ErrorCodeWinSock;
  265. public int SocketErrorCode;
  266. private static readonly string[] ProtocolIdToName = { "UDP", "TCP", "2(N/A)", "3(N/A)", "WS", "WSS", "6(N/A)", "7WebRTC" };
  267. private class SCSBitPos
  268. {
  269. /// <summary>28 and up. 4 bits.</summary>
  270. public const int Version = 28;
  271. /// <summary>25 and up. 3 bits.</summary>
  272. public const int UsedProtocol = 25;
  273. public const int EmptyBit = 24;
  274. public const int AppQuits = 23;
  275. public const int AppPause = 22;
  276. public const int AppPauseRecent = 21;
  277. public const int AppOutOfFocus = 20;
  278. public const int AppOutOfFocusRecent = 19;
  279. public const int NetworkReachable = 18;
  280. public const int ErrorCodeFits = 17;
  281. public const int ErrorCodeWinSock = 16;
  282. }
  283. /// <summary>
  284. /// Creates a SystemConnectionSummary for an incident of a local LoadBalancingClient. This gets used automatically by the LoadBalancingClient!
  285. /// </summary>
  286. /// <remarks>
  287. /// If the LoadBalancingClient.SystemConnectionSummary is non-null after a connection-loss, you can call .ToInt() and send this to analytics or log it.
  288. ///
  289. /// </remarks>
  290. /// <param name="client"></param>
  291. public SystemConnectionSummary(LoadBalancingClient client)
  292. {
  293. if (client != null)
  294. {
  295. // protocol = 3 bits! potentially adding WebRTC.
  296. this.UsedProtocol = (byte)((int)client.LoadBalancingPeer.UsedProtocol & 7);
  297. this.SocketErrorCode = (int)client.LoadBalancingPeer.SocketErrorCode;
  298. }
  299. this.AppQuits = ConnectionHandler.AppQuits;
  300. this.AppPause = ConnectionHandler.AppPause;
  301. this.AppPauseRecent = ConnectionHandler.AppPauseRecent;
  302. this.AppOutOfFocus = ConnectionHandler.AppOutOfFocus;
  303. this.AppOutOfFocusRecent = ConnectionHandler.AppOutOfFocusRecent;
  304. this.NetworkReachable = ConnectionHandler.IsNetworkReachableUnity();
  305. this.ErrorCodeFits = this.SocketErrorCode <= short.MaxValue; // socket error code <= short.Max (everything else is a problem)
  306. this.ErrorCodeWinSock = true;
  307. }
  308. /// <summary>
  309. /// Creates a SystemConnectionSummary instance from an int (reversing ToInt()). This can then be turned into a string again.
  310. /// </summary>
  311. /// <param name="summary">An int, as provided by ToInt(). No error checks yet.</param>
  312. public SystemConnectionSummary(int summary)
  313. {
  314. this.Version = GetBits(ref summary, SCSBitPos.Version, 0xF);
  315. this.UsedProtocol = GetBits(ref summary, SCSBitPos.UsedProtocol, 0x7);
  316. // 1 empty bit
  317. this.AppQuits = GetBit(ref summary, SCSBitPos.AppQuits);
  318. this.AppPause = GetBit(ref summary, SCSBitPos.AppPause);
  319. this.AppPauseRecent = GetBit(ref summary, SCSBitPos.AppPauseRecent);
  320. this.AppOutOfFocus = GetBit(ref summary, SCSBitPos.AppOutOfFocus);
  321. this.AppOutOfFocusRecent = GetBit(ref summary, SCSBitPos.AppOutOfFocusRecent);
  322. this.NetworkReachable = GetBit(ref summary, SCSBitPos.NetworkReachable);
  323. this.ErrorCodeFits = GetBit(ref summary, SCSBitPos.ErrorCodeFits);
  324. this.ErrorCodeWinSock = GetBit(ref summary, SCSBitPos.ErrorCodeWinSock);
  325. this.SocketErrorCode = summary & 0xFFFF;
  326. }
  327. /// <summary>
  328. /// Turns the SystemConnectionSummary into an integer, which can be be used for analytics purposes. It contains a lot of info and can be used to instantiate a new SystemConnectionSummary.
  329. /// </summary>
  330. /// <returns>Compact representation of the context for a disconnect issue.</returns>
  331. public int ToInt()
  332. {
  333. int result = 0;
  334. SetBits(ref result, this.Version, SCSBitPos.Version);
  335. SetBits(ref result, this.UsedProtocol, SCSBitPos.UsedProtocol);
  336. // 1 empty bit
  337. SetBit(ref result, this.AppQuits, SCSBitPos.AppQuits);
  338. SetBit(ref result, this.AppPause, SCSBitPos.AppPause);
  339. SetBit(ref result, this.AppPauseRecent, SCSBitPos.AppPauseRecent);
  340. SetBit(ref result, this.AppOutOfFocus, SCSBitPos.AppOutOfFocus);
  341. SetBit(ref result, this.AppOutOfFocusRecent, SCSBitPos.AppOutOfFocusRecent);
  342. SetBit(ref result, this.NetworkReachable, SCSBitPos.NetworkReachable);
  343. SetBit(ref result, this.ErrorCodeFits, SCSBitPos.ErrorCodeFits);
  344. SetBit(ref result, this.ErrorCodeWinSock, SCSBitPos.ErrorCodeWinSock);
  345. // insert socket error code as lower 2 bytes
  346. int socketErrorCode = this.SocketErrorCode & 0xFFFF;
  347. result |= socketErrorCode;
  348. return result;
  349. }
  350. /// <summary>
  351. /// A readable debug log string of the context for network problems.
  352. /// </summary>
  353. /// <returns>SystemConnectionSummary as readable string.</returns>
  354. public override string ToString()
  355. {
  356. StringBuilder sb = new StringBuilder();
  357. string transportProtocol = ProtocolIdToName[this.UsedProtocol];
  358. sb.Append($"SCS v{this.Version} {transportProtocol} SocketErrorCode: {this.SocketErrorCode} ");
  359. if (this.AppQuits) sb.Append("AppQuits ");
  360. if (this.AppPause) sb.Append("AppPause ");
  361. if (!this.AppPause && this.AppPauseRecent) sb.Append("AppPauseRecent ");
  362. if (this.AppOutOfFocus) sb.Append("AppOutOfFocus ");
  363. if (!this.AppOutOfFocus && this.AppOutOfFocusRecent) sb.Append("AppOutOfFocusRecent ");
  364. if (!this.NetworkReachable) sb.Append("NetworkUnreachable ");
  365. if (!this.ErrorCodeFits) sb.Append("ErrorCodeRangeExceeded ");
  366. if (this.ErrorCodeWinSock) sb.Append("WinSock");
  367. else sb.Append("BSDSock");
  368. string result = sb.ToString();
  369. return result;
  370. }
  371. public static bool GetBit(ref int value, int bitpos)
  372. {
  373. int result = (value >> bitpos) & 1;
  374. return result != 0;
  375. }
  376. public static byte GetBits(ref int value, int bitpos, byte mask)
  377. {
  378. int result = (value >> bitpos) & mask;
  379. return (byte)result;
  380. }
  381. /// <summary>Applies bitval to bitpos (no matter value's initial bit value).</summary>
  382. public static void SetBit(ref int value, bool bitval, int bitpos)
  383. {
  384. if (bitval)
  385. {
  386. value |= 1 << bitpos;
  387. }
  388. else
  389. {
  390. value &= ~(1 << bitpos);
  391. }
  392. }
  393. /// <summary>Applies bitvals via OR operation (expects bits in value to be 0 initially).</summary>
  394. public static void SetBits(ref int value, byte bitvals, int bitpos)
  395. {
  396. value |= bitvals << bitpos;
  397. }
  398. }
  399. }