using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using UnityEngine; namespace GeneralTools { public class WebSocketClient : SocketBase { Thread threadClient = null; ClientWebSocket ws = null; CancellationToken ct; string url = ""; float lastConnectedTime = 0; public WebSocketClient(string _url) { url = _url; separator = char.MinValue; InitSocket(_url); } protected async void InitSocket(string url) { try { await ClientConnet(); threadClient = new Thread(RecMsg); threadClient.IsBackground = true; threadClient.Start(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } async void RecMsg() { while (true) { if (socketClose) return; var result = new byte[reveiceByteSize]; try { await ws.ReceiveAsync(new ArraySegment(result), new CancellationToken());//接受数据 } catch (Exception e) { await ClientConnet(); } result = ByteCut(result, 0x00);//去除多余的数据 if (result.Length == 0) continue; RecordReceiveMsg(result, result.Length, null, null); } } public async override void SendMsg(string strMsg) { base.SendMsg(strMsg); try { byte[] _sendData = String2Bytes(strMsg, encoding); await ws.SendAsync(new ArraySegment(_sendData), WebSocketMessageType.Binary, true, ct); //发送数据 } catch (Exception) { await ClientConnet(); } } public async override void SendMsg(byte[] byteMsg) { base.SendMsg(byteMsg); try { await ws.SendAsync(new ArraySegment(byteMsg), WebSocketMessageType.Binary, true, ct); //发送数据 } catch (Exception) { await ClientConnet(); } } public async override void SocketQuit() { base.SocketQuit(); //关闭线程 if (threadClient != null) { threadClient.Interrupt(); threadClient.Abort(); } //最后关闭ws await CloseClient(); } async Task ClientConnet() { await CloseClient(); if (socketClose) return; if (nowTime - lastConnectedTime < reConnectedTime) return; lastConnectedTime = nowTime; ws = new ClientWebSocket(); ct = new CancellationToken(); Uri uri = new Uri(url); try { await ws.ConnectAsync(uri, ct); } catch (Exception) { } } async Task CloseClient() { if (ws != null) { try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, ws.CloseStatusDescription, ct); ws.Dispose(); ws = null; } catch (Exception) { } } } public static byte[] ByteCut(byte[] b, byte cut) { var list = new List(); list.AddRange(b); for (var i = list.Count - 1; i >= 0; i--) { if (list[i] == cut) list.RemoveAt(i); } var lastbyte = new byte[list.Count]; for (var i = 0; i < list.Count; i++) { lastbyte[i] = list[i]; } return lastbyte; } } }