ServerTime.cs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using UnityEngine.Networking;
  9. public class ServerTime : MonoBehaviour
  10. {
  11. #region Unity Singleton
  12. private static ServerTime _instance;
  13. public static ServerTime Instance
  14. {
  15. get
  16. {
  17. if (_instance == null)
  18. {
  19. _instance = FindObjectOfType(typeof(ServerTime)) as ServerTime;
  20. if (_instance == null)
  21. {
  22. AVDebug.LogError(string.Format("No gameObject with {0} component exists. Make sure to create a gameObject with {0} component", new System.Diagnostics.StackFrame().GetMethod().DeclaringType));
  23. }
  24. }
  25. return _instance;
  26. }
  27. }
  28. void Awake()
  29. {
  30. if (_instance != null && _instance != this)
  31. {
  32. AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
  33. Destroy(gameObject);
  34. return;
  35. }
  36. _instance = this;
  37. DontDestroyOnLoad(gameObject);
  38. StartCoroutine(LoadServerTimeRoutine());
  39. }
  40. private IEnumerator LoadServerTimeRoutine()
  41. {
  42. string url = GameConstants.SERVER_BASE_URL + "serverTime.php";
  43. var unityWebRequest = new UnityWebRequest(url);
  44. yield return new WaitForSeconds(3);
  45. //RetrieveServerTime(OnGetTime);
  46. StartCoroutine(AwaitRequest(unityWebRequest,Results));
  47. }
  48. private void Results(long obj)
  49. {
  50. Debug.Log(obj);
  51. }
  52. private void Percentage(UnityWebRequest arg1, ulong arg2)
  53. {
  54. throw new NotImplementedException();
  55. }
  56. private void OnGetTime(long l)
  57. {
  58. Debug.Log("OnGetTime " + l);
  59. }
  60. #endregion
  61. /// <summary>
  62. /// Returns the server time as a Unix Time Stamp, i.e. current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT),
  63. /// through the onComplete action.
  64. /// If there was an error, -1 is returned through the onComplete action
  65. /// </summary>
  66. public void RetrieveServerTime(Action<long> onComplete)
  67. {
  68. AVDebug.Assert(onComplete != null, "onComplete must not be null when requesting server time");
  69. StartCoroutine(RetrieveServerTimeCoroutine(onComplete));
  70. }
  71. internal IEnumerator AwaitRequest(UnityWebRequest request, Action<long> result)
  72. {
  73. WWW www = new WWW(GameConstants.SERVER_BASE_URL + "serverTime.php");
  74. yield return www;
  75. if (www.error != null)
  76. {
  77. result(-1);
  78. } else
  79. {
  80. long serverTime;
  81. if (long.TryParse(www.text, out serverTime))
  82. {
  83. result(serverTime);
  84. } else
  85. {
  86. result(-1); //parse error
  87. }
  88. }
  89. }
  90. private Action<long> _onComplete;
  91. IEnumerator RetrieveServerTimeCoroutine(Action<long> onComplete)
  92. {
  93. _onComplete = onComplete;
  94. Debug.Log("Start SEND SERVER TIME");
  95. //downloadData();
  96. string url = GameConstants.SERVER_BASE_URL + "serverTime.php";
  97. UnityWebRequest webrequest = UnityWebRequest.Get(url);
  98. yield return webrequest.SendWebRequest();
  99. Debug.Log("end SEND SERVER TIME");
  100. if (webrequest.isNetworkError || webrequest.isHttpError)
  101. {
  102. print("Network Error"); // return Unkown Error IOS Mobile
  103. onComplete(-1);
  104. }
  105. else
  106. {
  107. Debug.Log(webrequest.downloadHandler.text);
  108. long serverTime;
  109. if (long.TryParse(webrequest.downloadHandler.text, out serverTime))
  110. {
  111. onComplete(serverTime);
  112. } else
  113. {
  114. onComplete(-1); //parse error
  115. }
  116. }
  117. }
  118. void downloadData()
  119. {
  120. ThreadPool.QueueUserWorkItem(new WaitCallback(makeRequest));
  121. }
  122. private void makeRequest(object a)
  123. {
  124. string url = GameConstants.SERVER_BASE_URL + "serverTime.php";
  125. string result = "";
  126. var request = (HttpWebRequest)WebRequest.Create(url);
  127. //Speed up
  128. request.Proxy = null;
  129. using (var response = (HttpWebResponse)request.GetResponse())
  130. {
  131. var encoding = Encoding.GetEncoding(response.CharacterSet);
  132. using (var responseStream = response.GetResponseStream())
  133. using (var reader = new StreamReader(responseStream, encoding))
  134. result = reader.ReadToEnd();
  135. }
  136. long serverTime = -1;
  137. UnityThread.executeInUpdate(() =>
  138. {
  139. Debug.Log("end SEND SERVER TIME");
  140. if (long.TryParse(result, out serverTime))
  141. {
  142. _onComplete(serverTime);
  143. } else
  144. {
  145. _onComplete(-1); //parse error
  146. }
  147. });
  148. }
  149. }