WebSocketClient.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using BestHTTP.WebSocket;
  5. using System;
  6. using BestHTTP;
  7. using BestHTTP.Authentication;
  8. public class WebSocketClient : MonoBehaviour {
  9. // [SerializeField]
  10. // private string address = "wss://rtc.shadowcreator.com:3300";
  11. public static Dictionary<string, WebSocketClient> webSockets = new Dictionary<string, WebSocketClient>();
  12. private WebSocket _webSocket;
  13. private static bool init = false;
  14. // public static WebSocketClient Instance{ private set; get;}
  15. private string sName = "111";
  16. public delegate void OnWebSocketCloseDelegate ();
  17. public static OnWebSocketCloseDelegate OnWebSocketClose;
  18. public delegate void OnMessagedDelegate(string data);
  19. public OnMessagedDelegate OnMessaged;
  20. // Use this for initialization
  21. void Start ()
  22. {
  23. DontDestroyOnLoad(this.gameObject);
  24. // Invoke("Connect", 1f);
  25. // Connect();
  26. }
  27. void Awake()
  28. {
  29. //if (!init) {
  30. //Instance = this;
  31. //} else {
  32. // Destroy (this.gameObject);
  33. // return;
  34. //}
  35. }
  36. // Update is called once per frame
  37. void Update () {
  38. }
  39. void OnDestroy()
  40. {
  41. CloseWebSocket ();
  42. }
  43. void OnApplicationQuit()
  44. {
  45. CloseWebSocket ();
  46. }
  47. private void CloseWebSocket()
  48. {
  49. if (_webSocket != null) {
  50. webSockets.Remove(name);
  51. _webSocket.Close();
  52. _webSocket = null;
  53. }
  54. }
  55. void OnOpen(WebSocket ws)
  56. {
  57. Debug.Log("-WebSocket Open!\n");
  58. // StartCoroutine (Ping ());
  59. }
  60. public static float times;
  61. public static int count=0;
  62. public static int maxCount;
  63. void OnMessageReceived(WebSocket ws, string message)
  64. {
  65. // Debug.Log(message);
  66. /*
  67. times = times + Time.deltaTime;
  68. count++;
  69. if (times>1)
  70. {
  71. maxCount = count;
  72. count = 0;
  73. times = 0;
  74. }*/
  75. //
  76. OnMessage(message);
  77. }
  78. private void OnMessage(string data)
  79. {
  80. if (OnMessaged != null)
  81. {
  82. OnMessaged(data);
  83. }
  84. }
  85. void OnClosed(WebSocket ws, UInt16 code, string message)
  86. {
  87. string log = string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
  88. Debug.Log(log);
  89. if (OnWebSocketClose != null) {
  90. OnWebSocketClose ();
  91. }
  92. }
  93. void OnError(WebSocket ws, Exception ex)
  94. {
  95. Debug.Log("OnError");
  96. string errorMsg = string.Empty;
  97. #if !UNITY_WEBGL || UNITY_EDITOR
  98. if (ws.InternalRequest.Response != null)
  99. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  100. #endif
  101. string log = string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
  102. Debug.Log (log);
  103. webSockets.Remove(name);
  104. _webSocket = null;
  105. /*
  106. LoadManager.showClickPop ("网络异常,请重新登陆",ShadowSystem.Quit);*/
  107. }
  108. public void Connect()
  109. {
  110. Debug.Log("开始连接");
  111. webSockets.Add(sName, this);
  112. //_webSocket = new WebSocket(new Uri(NetworkConfiguration.socket_Url));
  113. _webSocket = new WebSocket(new Uri(NetworkConfiguration.socket_Url_test));
  114. _webSocket.InternalRequest.AddHeader("Sec-WebSocket-Protocol", "protoo");
  115. // _webSocket.Send
  116. //_webSocket.
  117. #if !UNITY_WEBGL
  118. _webSocket.StartPingThread = true;
  119. #if !BESTHTTP_DISABLE_PROXY
  120. if (HTTPManager.Proxy != null)
  121. {
  122. _webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
  123. Debug.Log("连接。。。。");
  124. }
  125. #endif
  126. #endif
  127. // Subscribe to the WS events
  128. _webSocket.OnOpen += OnOpen;
  129. _webSocket.OnMessage += OnMessageReceived;
  130. _webSocket.OnClosed += OnClosed;
  131. _webSocket.OnError += OnError;
  132. // Start connecting to the server
  133. _webSocket.Open();
  134. Debug.Log("开始连接Open");
  135. }
  136. IEnumerator Ping()
  137. {
  138. while (_webSocket != null) {
  139. yield return new WaitForSeconds (50);
  140. Debug.Log("Ping");
  141. Send ("Ping");
  142. }
  143. }
  144. public void Send(string message)
  145. {
  146. if (_webSocket != null)
  147. {
  148. //Debug.Log(message);
  149. _webSocket.Send (message);
  150. }
  151. }
  152. }