123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220 |
- using BestHTTP;
- using BestHTTP.Authentication;
- using BestHTTP.WebSocket;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using XRTool.Util;
- public class WebSocketClient : MonoBehaviour
- {
- // [SerializeField]
- // private string address = "wss://rtc.shadowcreator.com:3300";
- public static Dictionary<string, WebSocketClient> webSockets = new Dictionary<string, WebSocketClient>();
- public WebSocket _webSocket;
- private static bool init = false;
- // public static WebSocketClient Instance{ private set; get;}
- public string sName = "111";
- public delegate void OnWebSocketCloseDelegate(string data);
- public OnWebSocketCloseDelegate OnWebSocketClose;
- public delegate void OnWebSocketErrorDelegate(string data);
- public OnWebSocketErrorDelegate OnWebErrorClose;
- public delegate void OnMessagedDelegate(string data);
- public OnMessagedDelegate OnMessaged;
- // Use this for initialization
- void Start()
- {
- DontDestroyOnLoad(this.gameObject);
- // Invoke("Connect", 1f);
- // Connect();
- }
- void Awake()
- {
- //if (!init) {
- //Instance = this;
- //} else {
- // Destroy (this.gameObject);
- // return;
- //}
- }
- // Update is called once per frame
- void Update()
- {
- }
- void OnDestroy()
- {
- CloseWebSocket();
- }
- void OnApplicationQuit()
- {
- CloseWebSocket();
- }
- public void CloseWebSocket()
- {
- if (_webSocket != null)
- {
- webSockets.Remove(sName);
- _webSocket.Close();
- _webSocket = null;
- }
- }
- void OnOpen(WebSocket ws)
- {
- CommonMethod.HideNetLoading(sName);
- UnityLog.Log("-WebSocket Open!\n");
- // StartCoroutine (Ping ());
- }
- public static float times;
- public static int count = 0;
- public static int maxCount;
- public Queue<string> queue = new Queue<string>();
- public Queue<string> queueClose = new Queue<string>();
- public Queue<string> queueError = new Queue<string>();
- void OnMessageReceived(WebSocket ws, string message)
- {
- queue.Enqueue(message);
- /*
- times = times + Time.deltaTime;
- count++;
- if (times>1)
- {
- maxCount = count;
- count = 0;
- times = 0;
- }*/
- //
- }
- public void LateUpdate()
- {
- if (queue.Count > 0 && !CommonMethod.IsReceive)
- {
- int count = queue.Count;
- for (int i = 0; i < count; i++)
- {
- OnMessage(queue.Dequeue());
- }
- }
- if (queueClose.Count > 0)
- {
- OnSClosed(queueClose.Dequeue());
- }
- if (queueError.Count > 0)
- {
- OnSCErrord(queueError.Dequeue());
- }
- //if (queue != null && queue.Count > 0)
- //{
- // OnMessage(queue.Dequeue());
- //}
- }
- private void OnMessage(string data)
- {
- if (OnMessaged != null)
- {
- OnMessaged(data);
- }
- }
- private void OnSClosed(string data)
- {
- if (OnWebSocketClose != null)
- {
- OnWebSocketClose(data);
- }
- }
- private void OnSCErrord(string data)
- {
- CommonMethod.IsReceive = true;
- if (OnWebErrorClose != null)
- {
- OnWebErrorClose(data);
- }
- }
-
- void OnClosed(WebSocket ws, UInt16 code, string message)
- {
- string log = string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
- Debug.Log(log);
- queueClose.Enqueue(message);
- }
- void OnError(WebSocket ws, Exception ex)
- {
- CommonMethod.HideNetLoading(sName);
- Debug.Log("OnError");
- string errorMsg = string.Empty;
- #if !UNITY_WEBGL || UNITY_EDITOR
- if (ws.InternalRequest.Response != null)
- errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
- #endif
- string log = string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
- Debug.Log(log);
- webSockets.Remove(sName);
- _webSocket = null;
- queueError.Enqueue(log);
- /*
- LoadManager.showClickPop ("网络异常,请重新登陆",ShadowSystem.Quit);*/
- }
- public static int socketCount;
- public void Connect(string Url,string message)
- {
- socketCount++;
- sName = message + "_socket";
- CommonMethod.ShowNetLoading(sName,"正在连接"+ message+"服务器...");
- webSockets.Add(sName, this);
- // _webSocket = new WebSocket(new Uri(NetworkConfiguration.socket_Url));
- _webSocket = new WebSocket(new Uri(Url));
- _webSocket.InternalRequest.AddHeader("Sec-WebSocket-Protocol", "protoo");
- // _webSocket.Send
- //_webSocket.
- #if !UNITY_WEBGL
- _webSocket.StartPingThread = true;
- #if !BESTHTTP_DISABLE_PROXY
- if (HTTPManager.Proxy != null)
- {
- _webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
- }
- #endif
- #endif
- // Subscribe to the WS events
- _webSocket.OnOpen += OnOpen;
- _webSocket.OnMessage += OnMessageReceived;
- _webSocket.OnClosed += OnClosed;
- _webSocket.OnError += OnError;
- // Start connecting to the server
- _webSocket.Open();
- UnityLog.Log("开始连接Open" + Url);
- }
- IEnumerator Ping()
- {
- while (_webSocket != null)
- {
- yield return new WaitForSeconds(50);
- Send("Ping");
- }
- }
- public void Send(string message)
- {
- if (_webSocket != null)
- {
- _webSocket.Send(message);
- }
- }
- }
|