using SuperSocket.ClientEngine; using System; using System.Threading; using System.Threading.Tasks; using WebSocket4Net; namespace XHZB.Desktop.WebSocket { public class WSocketClient : IDisposable { public static NLog.Logger _Logger = NLog.LogManager.GetCurrentClassLogger(); #region 向外传递数据事件 public event Action MessageReceived; #endregion WebSocket4Net.WebSocket _webSocket; /// /// 检查重连线程 /// Thread _thread; bool _isRunning = true; /// /// WebSocket连接地址 /// public string ServerPath { get; set; } public WSocketClient(string url) { ServerPath = url; this._webSocket = new WebSocket4Net.WebSocket(url); this._webSocket.Opened += WebSocket_Opened; this._webSocket.Error += WebSocket_Error; this._webSocket.Closed += WebSocket_Closed; this._webSocket.MessageReceived += WebSocket_MessageReceived; } #region "web socket " /// /// 连接方法 /// public bool Start() { bool result = true; try { this._webSocket.Open(); this._isRunning = true; this._thread = new Thread(new ThreadStart(CheckConnection)); this._thread.Start(); } catch (Exception ex) { _Logger.Error(ex.ToString()); result = false; } return result; } /// /// 消息收到事件 /// /// /// void WebSocket_MessageReceived(object sender, MessageReceivedEventArgs e) { _Logger.Info(" Received:" + e.Message); MessageReceived?.Invoke(e.Message); } /// /// Socket关闭事件 /// /// /// void WebSocket_Closed(object sender, EventArgs e) { _Logger.Info("websocket_Closed"); } /// /// Socket报错事件 /// /// /// void WebSocket_Error(object sender, ErrorEventArgs e) { _Logger.Info("websocket_Error:" + e.Exception.ToString()); } /// /// Socket打开事件 /// /// /// void WebSocket_Opened(object sender, EventArgs e) { _Logger.Info(" websocket_Opened"); } /// /// 检查重连线程 /// private void CheckConnection() { do { try { if (this._webSocket.State != WebSocket4Net.WebSocketState.Open && this._webSocket.State != WebSocket4Net.WebSocketState.Connecting) { _Logger.Info(" Reconnect websocket WebSocketState:" + this._webSocket.State); this._webSocket.Close(); this._webSocket.Open(); Console.WriteLine("正在重连"); } } catch (Exception ex) { _Logger.Error(ex.ToString()); } System.Threading.Thread.Sleep(5000); } while (this._isRunning); } #endregion /// /// 发送消息 /// /// public void SendMessage(string Message) { Task.Factory.StartNew(() => { if (_webSocket != null && _webSocket.State == WebSocket4Net.WebSocketState.Open) { this._webSocket.Send(Message); } }); } public void Dispose() { this._isRunning = false; try { _thread.Abort(); } catch { } this._webSocket.Close(); this._webSocket.Dispose(); this._webSocket = null; } } }