WebSocketClient.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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.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. queue.Enqueue(message);
  76. /*
  77. times = times + Time.deltaTime;
  78. count++;
  79. if (times>1)
  80. {
  81. maxCount = count;
  82. count = 0;
  83. times = 0;
  84. }*/
  85. //
  86. }
  87. public void LateUpdate()
  88. {
  89. if (queue.Count > 0 && !CommonMethod.IsReceive)
  90. {
  91. int count = queue.Count;
  92. for (int i = 0; i < count; i++)
  93. {
  94. OnMessage(queue.Dequeue());
  95. }
  96. }
  97. if (queueClose.Count > 0)
  98. {
  99. OnSClosed(queueClose.Dequeue());
  100. }
  101. if (queueError.Count > 0)
  102. {
  103. OnSCErrord(queueError.Dequeue());
  104. }
  105. //if (queue != null && queue.Count > 0)
  106. //{
  107. // OnMessage(queue.Dequeue());
  108. //}
  109. }
  110. private void OnMessage(string data)
  111. {
  112. if (OnMessaged != null)
  113. {
  114. OnMessaged(data);
  115. }
  116. }
  117. private void OnSClosed(string data)
  118. {
  119. if (OnWebSocketClose != null)
  120. {
  121. OnWebSocketClose(data);
  122. }
  123. }
  124. private void OnSCErrord(string data)
  125. {
  126. CommonMethod.IsReceive = true;
  127. if (OnWebErrorClose != null)
  128. {
  129. OnWebErrorClose(data);
  130. }
  131. }
  132. void OnClosed(WebSocket ws, UInt16 code, string message)
  133. {
  134. string log = string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
  135. Debug.Log(log);
  136. queueClose.Enqueue(message);
  137. }
  138. void OnError(WebSocket ws, Exception ex)
  139. {
  140. CommonMethod.HideNetLoading(sName);
  141. Debug.Log("OnError");
  142. string errorMsg = string.Empty;
  143. #if !UNITY_WEBGL || UNITY_EDITOR
  144. if (ws.InternalRequest.Response != null)
  145. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  146. #endif
  147. string log = string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
  148. Debug.Log(log);
  149. webSockets.Remove(sName);
  150. _webSocket = null;
  151. queueError.Enqueue(log);
  152. /*
  153. LoadManager.showClickPop ("网络异常,请重新登陆",ShadowSystem.Quit);*/
  154. }
  155. public static int socketCount;
  156. public void Connect(string Url,string message)
  157. {
  158. socketCount++;
  159. sName = message + "_socket";
  160. CommonMethod.ShowNetLoading(sName,"正在连接"+ message+"服务器...");
  161. webSockets.Add(sName, this);
  162. // _webSocket = new WebSocket(new Uri(NetworkConfiguration.socket_Url));
  163. _webSocket = new WebSocket(new Uri(Url));
  164. _webSocket.InternalRequest.AddHeader("Sec-WebSocket-Protocol", "protoo");
  165. // _webSocket.Send
  166. //_webSocket.
  167. #if !UNITY_WEBGL
  168. _webSocket.StartPingThread = true;
  169. #if !BESTHTTP_DISABLE_PROXY
  170. if (HTTPManager.Proxy != null)
  171. {
  172. _webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
  173. }
  174. #endif
  175. #endif
  176. // Subscribe to the WS events
  177. _webSocket.OnOpen += OnOpen;
  178. _webSocket.OnMessage += OnMessageReceived;
  179. _webSocket.OnClosed += OnClosed;
  180. _webSocket.OnError += OnError;
  181. // Start connecting to the server
  182. _webSocket.Open();
  183. UnityLog.Log("开始连接Open" + Url);
  184. }
  185. IEnumerator Ping()
  186. {
  187. while (_webSocket != null)
  188. {
  189. yield return new WaitForSeconds(50);
  190. Send("Ping");
  191. }
  192. }
  193. public void Send(string message)
  194. {
  195. if (_webSocket != null)
  196. {
  197. _webSocket.Send(message);
  198. }
  199. }
  200. }