WebSocketClient.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. using BestHTTP;
  2. using BestHTTP.Authentication;
  3. using BestHTTP.WebSocket;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using UnityEngine;
  8. using XRTool.Util;
  9. public class WebSocketClient : MonoBehaviour
  10. {
  11. // [SerializeField]
  12. // private string address = "wss://rtc.shadowcreator.com:3300";
  13. public static Dictionary<string, WebSocketClient> webSockets = new Dictionary<string, WebSocketClient>();
  14. public WebSocket _webSocket;
  15. private static bool init = false;
  16. // public static WebSocketClient Instance{ private set; get;}
  17. public string sName = "111";
  18. public delegate void OnWebSocketCloseDelegate(string data);
  19. public OnWebSocketCloseDelegate OnWebSocketClose;
  20. public delegate void OnWebSocketErrorDelegate(string data);
  21. public OnWebSocketErrorDelegate OnWebErrorClose;
  22. public delegate void OnMessagedDelegate(string data);
  23. public OnMessagedDelegate OnMessaged;
  24. // Use this for initialization
  25. void Start()
  26. {
  27. DontDestroyOnLoad(this.gameObject);
  28. // Invoke("Connect", 1f);
  29. // Connect();
  30. }
  31. void Awake()
  32. {
  33. //if (!init) {
  34. //Instance = this;
  35. //} else {
  36. // Destroy (this.gameObject);
  37. // return;
  38. //}
  39. }
  40. // Update is called once per frame
  41. void Update()
  42. {
  43. }
  44. void OnDestroy()
  45. {
  46. CloseWebSocket();
  47. }
  48. void OnApplicationQuit()
  49. {
  50. CloseWebSocket();
  51. }
  52. public void CloseWebSocket()
  53. {
  54. if (_webSocket != null)
  55. {
  56. webSockets.Remove(sName);
  57. _webSocket.Close();
  58. _webSocket = null;
  59. }
  60. }
  61. void OnOpen(WebSocket ws)
  62. {
  63. CommonMethod.HideNetLoading(sName);
  64. UnityLog.Instance.Log("-WebSocket Open!\n");
  65. // StartCoroutine (Ping ());
  66. }
  67. public static float times;
  68. public static int count = 0;
  69. public static int maxCount;
  70. public Queue<string> queue = new Queue<string>();
  71. public Queue<string> queueClose = new Queue<string>();
  72. public Queue<string> queueError = new Queue<string>();
  73. void OnMessageReceived(WebSocket ws, string message)
  74. {
  75. // Debug.Log("================>" + message);
  76. queue.Enqueue(message);
  77. /*
  78. times = times + Time.deltaTime;
  79. count++;
  80. if (times>1)
  81. {
  82. maxCount = count;
  83. count = 0;
  84. times = 0;
  85. }*/
  86. //
  87. }
  88. public void LateUpdate()
  89. {
  90. if (queue.Count > 0 && (!CommonMethod.IsReceive||sName== "音视频_socket"))
  91. {
  92. int count = queue.Count;
  93. for (int i = 0; i < count; i++)
  94. {
  95. OnMessage(queue.Dequeue());
  96. }
  97. }
  98. if (queueClose.Count > 0)
  99. {
  100. OnSClosed(queueClose.Dequeue());
  101. }
  102. if (queueError.Count > 0)
  103. {
  104. OnSCErrord(queueError.Dequeue());
  105. }
  106. //if (queue != null && queue.Count > 0)
  107. //{
  108. // OnMessage(queue.Dequeue());
  109. //}
  110. }
  111. private void OnMessage(string data)
  112. {
  113. if (OnMessaged != null)
  114. {
  115. OnMessaged(data);
  116. }
  117. }
  118. private void OnSClosed(string data)
  119. {
  120. if (OnWebSocketClose != null)
  121. {
  122. OnWebSocketClose(data);
  123. }
  124. }
  125. private void OnSCErrord(string data)
  126. {
  127. CommonMethod.IsReceive = true;
  128. if (OnWebErrorClose != null)
  129. {
  130. OnWebErrorClose(data);
  131. }
  132. }
  133. void OnClosed(WebSocket ws, UInt16 code, string message)
  134. {
  135. string log = string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
  136. Debug.Log(log);
  137. queueClose.Enqueue(message);
  138. }
  139. void OnError(WebSocket ws, Exception ex)
  140. {
  141. CommonMethod.HideNetLoading(sName);
  142. Debug.Log("OnError");
  143. string errorMsg = string.Empty;
  144. #if !UNITY_WEBGL || UNITY_EDITOR
  145. if (ws.InternalRequest.Response != null)
  146. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  147. #endif
  148. string log = string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
  149. Debug.Log(log);
  150. webSockets.Remove(sName);
  151. _webSocket = null;
  152. queueError.Enqueue(log);
  153. /*
  154. LoadManager.showClickPop ("网络异常,请重新登陆",ShadowSystem.Quit);*/
  155. }
  156. public static int socketCount;
  157. public void Connect(string Url,string message)
  158. {
  159. socketCount++;
  160. sName = message + "_socket";
  161. CommonMethod.ShowNetLoading(sName,"正在连接"+ message+"服务器...");
  162. if (webSockets.ContainsKey(sName))
  163. {
  164. webSockets[sName] = this;
  165. }
  166. else
  167. {
  168. webSockets.Add(sName, this);
  169. }
  170. // _webSocket = new WebSocket(new Uri(NetworkConfiguration.socket_Url));
  171. _webSocket = new WebSocket(new Uri(Url));
  172. _webSocket.InternalRequest.AddHeader("Sec-WebSocket-Protocol", "protoo");
  173. // _webSocket.Send
  174. //_webSocket.
  175. #if !UNITY_WEBGL
  176. _webSocket.StartPingThread = true;
  177. #if !BESTHTTP_DISABLE_PROXY
  178. if (HTTPManager.Proxy != null)
  179. {
  180. _webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
  181. }
  182. #endif
  183. #endif
  184. // Subscribe to the WS events
  185. _webSocket.OnOpen += OnOpen;
  186. _webSocket.OnMessage += OnMessageReceived;
  187. _webSocket.OnClosed += OnClosed;
  188. _webSocket.OnError += OnError;
  189. // Start connecting to the server
  190. _webSocket.Open();
  191. UnityLog.Instance.Log("开始连接Open" + Url);
  192. }
  193. IEnumerator Ping()
  194. {
  195. while (_webSocket != null)
  196. {
  197. yield return new WaitForSeconds(50);
  198. Send("Ping");
  199. }
  200. }
  201. public void Send(string message)
  202. {
  203. if (_webSocket != null)
  204. {
  205. _webSocket.Send(message);
  206. }
  207. }
  208. }