// ---------------------------------------------------------------------------- // // Photon Realtime API - Copyright (C) 2022 Exit Games GmbH // // // Utility class to keep a clients connection, even if not used otherwise. // // developer@photonengine.com // ---------------------------------------------------------------------------- #if UNITY_2017_4_OR_NEWER #define SUPPORTED_UNITY #endif namespace Photon.Realtime { using System; using System.Text; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using Photon.Client; #if SUPPORTED_UNITY using UnityEngine; #endif /// Handler class to use threading to keep a RealtimeClient connection alive (calling SendAcksOnly if it was not called in time). #if SUPPORTED_UNITY public class ConnectionHandler : MonoBehaviour #else public class ConnectionHandler #endif { /// /// Photon client to log information and statistics from. /// public RealtimeClient Client { get; set; } /// Optional string identifier for the instance (for debugging). public string Id; /// Option to let the fallback thread call Disconnect after the KeepAliveInBackground time. Default: false. /// /// If set to true, the thread will disconnect the client regularly, should the client not call SendOutgoingCommands / Service. /// This may happen due to an app being in background (and not getting a lot of CPU time) or when loading assets. /// /// If false, a regular timeout time will have to pass (on top) to time out the client. /// [Obsolete("After the KeepAliveInBackground, the client will always properly disconnect with DisconnectCause.ClientServiceInactivity.")] [NonSerialized] public bool DisconnectAfterKeepAlive = false; /// Defines for how long the Fallback Thread should keep the connection, before it may time out as usual. /// 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. public int KeepAliveInBackground = 60000; /// Counts how often the Fallback Thread called SendAcksOnly, which is purely of interest to monitor if the game logic called SendOutgoingCommands as intended. public int CountSendAcksOnly { get; private set; } /// True if a fallback thread is running. Will call the client's SendAcksOnly() method to keep the connection up. public bool FallbackThreadRunning { get; private set; } /// Indicates that the app is closing. Set in OnApplicationQuit(). [NonSerialized] public static bool AppQuits; /// Indicates that the (Unity) app is Paused. This means the main thread is not running. [NonSerialized] public static bool AppPause; /// Indicates that the app was paused within the last 5 seconds. [NonSerialized] public static bool AppPauseRecent; /// Indicates that the app is not in focus. [NonSerialized] public static bool AppOutOfFocus; /// Indicates that the app was out of focus within the last 5 seconds. [NonSerialized] public static bool AppOutOfFocusRecent; private bool didSendAcks; private bool didWarnAboutMissingService; private int timeWarnAboutMissingService = 5000; private readonly Stopwatch backgroundStopwatch = new Stopwatch(); private Timer stateTimer; /// /// Creates an instance of the ConnectionHandler, assigns the given client. In Unity this uses a single GameObject to store all components on and applies DontDestroyOnLoad. /// /// The client to handle. /// Optional ID for this handle (could be based / related to the client instance). /// public static ConnectionHandler BuildInstance(RealtimeClient client, string id = null) { ConnectionHandler result; #if SUPPORTED_UNITY if (go == null) { go = new GameObject(nameof(ConnectionHandler)); if (Application.isPlaying) { DontDestroyOnLoad(go); } } result = go.AddComponent(); #else result = new ConnectionHandler(); #endif result.Id = id; result.Client = client; return result; } /// Stopping the fallback thread. In Unity, calls Destroy(this). public void RemoveInstance() { #if SUPPORTED_UNITY Destroy(this); #else this.StopFallbackSendAckThread(); #endif } #if SUPPORTED_UNITY private static GameObject go; #if UNITY_2019_4_OR_NEWER /// Resets static values to replace domain reload. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void StaticReset() { go = null; AppQuits = false; AppPause = false; AppPauseRecent = false; AppOutOfFocus = false; AppOutOfFocusRecent = false; } #endif /// Startup check if a Client is set (which is mandatory). protected virtual void Start() { if (this.Client == null) { UnityEngine.Debug.LogError("A ConnectionHandler should not be put into a scene. It is created by RealtimeClient.ConnectUsingSettings().", this); } } /// Starts the fallback thread automatically. protected virtual void OnEnable() { this.StartFallbackSendAckThread(); } /// Stops the fallback thread automatically. protected virtual void OnDisable() { this.StopFallbackSendAckThread(); } /// Called by Unity when the application gets closed. The UnityEngine will also call OnDisable. protected void OnApplicationQuit() { AppQuits = true; if (this.Client != null && this.Client.IsConnected) { this.Client.Disconnect(DisconnectCause.ApplicationQuit); this.Client.RealtimePeer.IsSimulationEnabled = false; } } /// Called by Unity when the application gets paused or resumed. public void OnApplicationPause(bool pause) { AppPause = pause; if (pause) { AppPauseRecent = true; this.CancelInvoke(nameof(this.ResetAppPauseRecent)); } else { Invoke(nameof(this.ResetAppPauseRecent), 5f); } } private void ResetAppPauseRecent() { AppPauseRecent = false; } /// Called by Unity when the application changes focus. public void OnApplicationFocus(bool focus) { AppOutOfFocus = !focus; if (!focus) { AppOutOfFocusRecent = true; this.CancelInvoke(nameof(this.ResetAppOutOfFocusRecent)); } else { this.Invoke(nameof(this.ResetAppOutOfFocusRecent), 5f); } } private void ResetAppOutOfFocusRecent() { AppOutOfFocusRecent = false; } #endif /// /// When run in Unity, this returns Application.internetReachability != NetworkReachability.NotReachable. /// /// Application.internetReachability != NetworkReachability.NotReachable public static bool IsNetworkReachableUnity() { #if SUPPORTED_UNITY return Application.internetReachability != NetworkReachability.NotReachable; #else return true; #endif } /// Starts periodic calls of RealtimeFallbackThread. public void StartFallbackSendAckThread() { #if UNITY_WEBGL if (!this.FallbackThreadRunning) this.InvokeRepeating(nameof(this.RealtimeFallbackInvoke), 0.05f, 0.05f); #else if (this.stateTimer != null) { return; } stateTimer = new Timer(this.RealtimeFallback, null, 50, 50); #endif this.FallbackThreadRunning = true; } /// Stops the periodic calls of RealtimeFallbackThread. public void StopFallbackSendAckThread() { #if UNITY_WEBGL if (this.FallbackThreadRunning) this.CancelInvoke(nameof(this.RealtimeFallbackInvoke)); #else if (this.stateTimer != null) { this.stateTimer.Dispose(); this.stateTimer = null; } #endif this.FallbackThreadRunning = false; } /// Used in WebGL builds which can't call RealtimeFallback(object state = null) with the state context parameter. public void RealtimeFallbackInvoke() { this.RealtimeFallback(); } /// A thread which runs independently of the Update() calls. Keeps connections online while loading or in background. See . public void RealtimeFallback(object state = null) { if (this.Client == null) { return; } //Log.Warn($"PeerId {this.Client.RealtimePeer.PeerID} RealtimeFallback {this.Client.IsConnected}. {this.Client.RealtimePeer.ConnectionTime} - {this.Client.RealtimePeer.Stats.LastSendOutgoingTimestamp} = {this.Client.RealtimePeer.ConnectionTime - this.Client.RealtimePeer.Stats.LastSendOutgoingTimestamp} backgroundStopwatch.ElapsedMilliseconds: {this.backgroundStopwatch.ElapsedMilliseconds.ToString("N0")}"); if (this.Client.IsConnected && this.Client.RealtimePeer.ConnectionTime - this.Client.RealtimePeer.Stats.LastSendOutgoingTimestamp > 100) { if (!this.didSendAcks) { this.backgroundStopwatch.Restart(); } // the client should disconnect after some seconds in background - this component gets cleaned up in OnDisconnected(). // this runs on the timer thread, so only the thread-safe DisconnectFromFallbackThread() may be used here. it notifies // the server right away; the client-side State change and callbacks follow with the next DispatchIncomingCommands(). if (this.backgroundStopwatch.ElapsedMilliseconds > this.KeepAliveInBackground) { this.Client.DisconnectFromFallbackThread(); this.StopFallbackSendAckThread(); return; } this.didSendAcks = true; this.CountSendAcksOnly++; // one time logging to warn about lack of service calls after 5 sec if (!this.didWarnAboutMissingService && this.backgroundStopwatch.ElapsedMilliseconds > this.timeWarnAboutMissingService) { this.didWarnAboutMissingService = true; if (this.Client.State == ClientState.Disconnecting) { Log.Warn($"The RealtimeClient is in Disconnecting state but DispatchIncomingCommands() wasn't called for > {timeWarnAboutMissingService/1000} seconds. Continue to call DispatchIncomingCommands() after Disconnect() to get the OnDisconnected callback.", this.Client.LogLevel, this.Client.LogPrefix); } else { Log.Warn($"RealtimeClient.SendOutgoingCommands() was not called for > {timeWarnAboutMissingService/1000} seconds. After the KeepAliveInBackground ({this.KeepAliveInBackground/1000}sec) this causes a disconnect.", this.Client.LogLevel, this.Client.LogPrefix); } } this.Client.RealtimePeer.SendAcksOnly(); } else { // not connected or the LastSendOutgoingTimestamp was below the threshold if (this.backgroundStopwatch.IsRunning) { this.backgroundStopwatch.Reset(); } this.didSendAcks = false; } } } /// /// The SystemConnectionSummary (SBS) is useful to analyze low level connection issues in Unity. This requires a ConnectionHandler in the scene. /// /// /// A RealtimeClient automatically creates a SystemConnectionSummary on these disconnect causes: /// DisconnectCause.ExceptionOnConnect, DisconnectCause.Exception, DisconnectCause.ServerTimeout and DisconnectCause.ClientTimeout. /// /// The SBS can then be turned into an integer (ToInt()) or string to debug the situation or use in analytics. /// Both, ToString and ToInt summarize the network-relevant conditions of the client at and before the connection fail, including the PhotonPeer.SocketErrorCode. /// /// Important: To correctly create the SBS instance, a ConnectionHandler component must be present and enabled in the /// Unity scene hierarchy. In best case, keep the ConnectionHandler on a GameObject which is flagged as /// DontDestroyOnLoad. /// public class SystemConnectionSummary { // SystemConditionSummary v0 has 32 bits: // Version bits (4 bits) // UDP, TCP, WS, WSS (WebRTC potentially) (3 bits) // 1 bit empty // // AppQuits // AppPause // AppPauseRecent // AppOutOfFocus // // AppOutOfFocusRecent // NetworkReachability (Unity value) // ErrorCodeFits (ErrorCode > short.Max would be a problem) // WinSock (true) or BSD (false) Socket Error Codes // // -> 12 of upper 16 bits are used // // lower 2 bytes are the Socket Error Code (capped to 0xFFFF) /// Version of the SystemConnectionSummary type. public readonly byte Version = 0; /// Which protocol is used. Refer to ConnectionProtocol. public byte UsedProtocol; /// True if the Unity app is closing / shut down. public bool AppQuits; /// True if the Unity app is paused. public bool AppPause; /// True if the Unity app was paused recently (past 5 sec). public bool AppPauseRecent; /// True if the Unity app is out of focus / minimized. public bool AppOutOfFocus; /// True if the Unity app was out of focus / minimized recently (past 5 sec). public bool AppOutOfFocusRecent; /// True if the Unity engine tells us the network is reachable. public bool NetworkReachable; /// True if the Socket-level error code fits into the usual byte "budget". public bool ErrorCodeFits; /// True if the Socket-level error code is WinSock based. public bool ErrorCodeWinSock; /// Socket-level error code (if any is available). public int SocketErrorCode; private static readonly string[] ProtocolIdToName = { "UDP", "TCP", "2(N/A)", "3(N/A)", "WS", "WSS", "6(N/A)", "7WebRTC" }; internal class SCSBitPos { /// 28 and up. 4 bits. internal const int Version = 28; /// 25 and up. 3 bits. internal const int UsedProtocol = 25; /// Position of an empty bit. internal const int EmptyBit = 24; /// App Quits was called bit. internal const int AppQuits = 23; /// App Pause was called bit. internal const int AppPause = 22; /// App Quits was called recently bit. internal const int AppPauseRecent = 21; /// App not in focus bit. internal const int AppOutOfFocus = 20; /// App not in focus recently bit. internal const int AppOutOfFocusRecent = 19; /// Unity signals network is reachable bit. internal const int NetworkReachable = 18; /// ErrorCode is small enough to fit bit. internal const int ErrorCodeFits = 17; /// Error code is of WinSock type bit. internal const int ErrorCodeWinSock = 16; } /// Brief error description per Windows socket error code. static readonly Dictionary UdpSocketErrors = new Dictionary { { 10004, "WSAEINTR - interrupted (temp)" }, { 10009, "WSAEBADF - bad file descriptor (fatal)" }, { 10013, "WSAEACCES - blocked by filter or missing SO_BROADCAST (fatal)" }, { 10014, "WSAEFAULT - invalid buffer pointer (fatal)" }, { 10022, "WSAEINVAL - socket not bound or invalid argument (fatal)" }, { 10035, "WSAEWOULDBLOCK - buffer full or no data yet (temp)" }, { 10036, "WSAEINPROGRESS - operation in progress (temp)" }, { 10038, "WSAENOTSOCK - socket handle invalid (fatal)" }, { 10039, "WSAEDESTADDRREQ - destination address required (fatal)" }, { 10040, "WSAEMSGSIZE - send: datagram too large / receive: datagram truncated (fatal)" }, { 10049, "WSAEADDRNOTAVAIL - cannot assign requested address (fatal)" }, { 10050, "WSAENETDOWN - network subsystem failed (fatal)" }, { 10051, "WSAENETUNREACH - network unreachable (fatal)" }, { 10054, "WSAECONNRESET - ICMP port unreachable from remote (fatal)" }, { 10055, "WSAENOBUFS - buffer exhaustion (temp)" }, { 10057, "WSAENOTCONN - socket not connected (fatal)" }, { 10058, "WSAESHUTDOWN - cannot send after socket shutdown (fatal)" }, // server address would be interesting { 10061, "WSAECONNREFUSED - connection actively refused (fatal)" }, { 10064, "WSAEHOSTDOWN - host is down (fatal)" }, { 10065, "WSAEHOSTUNREACH - host unreachable, no route (fatal)" }, }; /// /// Creates a SystemConnectionSummary for an incident of a local RealtimeClient. This gets used automatically by the RealtimeClient! /// /// /// If the RealtimeClient.SystemConnectionSummary is non-null after a connection-loss, you can call .ToInt() and send this to analytics or log it. /// /// /// public SystemConnectionSummary(RealtimeClient client) { if (client != null) { // protocol = 3 bits! potentially adding WebRTC. this.UsedProtocol = (byte)((int)client.RealtimePeer.UsedProtocol & 7); this.SocketErrorCode = (int)client.RealtimePeer.SocketErrorCode; } this.AppQuits = ConnectionHandler.AppQuits; this.AppPause = ConnectionHandler.AppPause; this.AppPauseRecent = ConnectionHandler.AppPauseRecent; this.AppOutOfFocus = ConnectionHandler.AppOutOfFocus; this.AppOutOfFocusRecent = ConnectionHandler.AppOutOfFocusRecent; this.NetworkReachable = ConnectionHandler.IsNetworkReachableUnity(); this.ErrorCodeFits = this.SocketErrorCode >= 0 && this.SocketErrorCode <= ushort.MaxValue; // socket error code fits in 4 bytes this.ErrorCodeWinSock = true; } /// /// Creates a SystemConnectionSummary instance from an int (reversing ToInt()). This can then be turned into a string again. /// /// An int, as provided by ToInt(). No error checks yet. public SystemConnectionSummary(int summary) { this.Version = GetBits(ref summary, SCSBitPos.Version, 0xF); this.UsedProtocol = GetBits(ref summary, SCSBitPos.UsedProtocol, 0x7); // 1 empty bit this.AppQuits = GetBit(ref summary, SCSBitPos.AppQuits); this.AppPause = GetBit(ref summary, SCSBitPos.AppPause); this.AppPauseRecent = GetBit(ref summary, SCSBitPos.AppPauseRecent); this.AppOutOfFocus = GetBit(ref summary, SCSBitPos.AppOutOfFocus); this.AppOutOfFocusRecent = GetBit(ref summary, SCSBitPos.AppOutOfFocusRecent); this.NetworkReachable = GetBit(ref summary, SCSBitPos.NetworkReachable); this.ErrorCodeFits = GetBit(ref summary, SCSBitPos.ErrorCodeFits); this.ErrorCodeWinSock = GetBit(ref summary, SCSBitPos.ErrorCodeWinSock); this.SocketErrorCode = summary & 0xFFFF; } /// /// Turns the SystemConnectionSummary into an integer, which can be used for analytics purposes. It contains a lot of info and can be used to instantiate a new SystemConnectionSummary. /// /// Compact representation of the context for a disconnect issue. public int ToInt() { int result = 0; SetBits(ref result, this.Version, SCSBitPos.Version); SetBits(ref result, this.UsedProtocol, SCSBitPos.UsedProtocol); // 1 empty bit SetBit(ref result, this.AppQuits, SCSBitPos.AppQuits); SetBit(ref result, this.AppPause, SCSBitPos.AppPause); SetBit(ref result, this.AppPauseRecent, SCSBitPos.AppPauseRecent); SetBit(ref result, this.AppOutOfFocus, SCSBitPos.AppOutOfFocus); SetBit(ref result, this.AppOutOfFocusRecent, SCSBitPos.AppOutOfFocusRecent); SetBit(ref result, this.NetworkReachable, SCSBitPos.NetworkReachable); SetBit(ref result, this.ErrorCodeFits, SCSBitPos.ErrorCodeFits); SetBit(ref result, this.ErrorCodeWinSock, SCSBitPos.ErrorCodeWinSock); // insert socket error code as lower 2 bytes int socketErrorCode = this.SocketErrorCode & 0xFFFF; result |= socketErrorCode; return result; } /// /// A readable debug log string of the context for network problems. /// /// SystemConnectionSummary as readable string. public override string ToString() { StringBuilder sb = new StringBuilder(); string transportProtocol = ProtocolIdToName[this.UsedProtocol]; string annotation = ""; UdpSocketErrors.TryGetValue(this.SocketErrorCode, out annotation); sb.Append($"SCS v{this.Version} {transportProtocol} SocketError: {this.SocketErrorCode} "); if (!string.IsNullOrEmpty(annotation)) sb.Append($"[{annotation}] "); if (this.AppQuits) sb.Append("AppQuits "); if (this.AppPause) sb.Append("AppPause "); if (!this.AppPause && this.AppPauseRecent) sb.Append("AppPauseRecent "); if (this.AppOutOfFocus) sb.Append("AppOutOfFocus "); if (!this.AppOutOfFocus && this.AppOutOfFocusRecent) sb.Append("AppOutOfFocusRecent "); if (!this.NetworkReachable) sb.Append("NetworkUnreachable "); if (!this.ErrorCodeFits) sb.Append("ErrorCodeRangeExceeded "); if (!this.ErrorCodeWinSock) sb.Append("BSDSock"); string result = sb.ToString(); return result; } /// Extracts the recorded error code from a SystemConnectionSummary binary representation. /// Pass the value of SystemConnectionSummary.ToInt(). /// Error code from a SCS summary (int) or -1 if the version can't be read. public static int GetErrorCode(int summary) { byte version = GetBits(ref summary, SCSBitPos.Version, 0xF); if (version == 0) { // in SCS v0, the error code is put into the last 2 bytes of an int return summary & 0xFFFF; } return -1; } /// Gets a specific bit out of the value at the given position. internal static bool GetBit(ref int value, int bitpos) { int result = (value >> bitpos) & 1; return result != 0; } /// Gets bitvals out of the value at the given position. internal static byte GetBits(ref int value, int bitpos, byte mask) { int result = (value >> bitpos) & mask; return (byte)result; } /// Applies bitval to bitpos (no matter value's initial bit value). internal static void SetBit(ref int value, bool bitval, int bitpos) { if (bitval) { value |= 1 << bitpos; } else { value &= ~(1 << bitpos); } } /// Applies bitvals via OR operation (expects bits in value to be 0 initially). internal static void SetBits(ref int value, byte bitvals, int bitpos) { value |= bitvals << bitpos; } } }