|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- using Common.system;
- using SuperSocket.ClientEngine;
- using System;
- using System.Collections.Generic;
- using System.Threading;
- using System.Threading.Tasks;
- using WebSocket4Net;
- using XHZB.Model;
-
- namespace XHZB.Desktop.WebSocket
- {
- public class WSocketClient : IDisposable
- {
- // 打开的窗口列表
- private static readonly Dictionary<Type, object> WinDic = new Dictionary<Type, object>();
- private static WSocketClient instance;
- public static WSocketClient getInstance()
- {
- if (instance == null)
- {
- instance = new WSocketClient();
- }
- return instance;
- }
-
-
-
-
-
-
- public static NLog.Logger _Logger = NLog.LogManager.GetCurrentClassLogger();
-
- #region 向外传递数据事件
- public event Action<string> MessageReceived;
- #endregion
-
- WebSocket4Net.WebSocket _webSocket;
- /// <summary>
- /// 检查重连线程
- /// </summary>
- Thread _thread;
- bool _isRunning = true;
- /// <summary>
- /// WebSocket连接地址
- /// </summary>
- public string ServerPath { get; set; }
-
- //public WSocketClient()
- //{
- // string url = "ws://schoolwstest.xhkjedu.com/ws";
- // 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;
-
- // //注册消息接收事件,接收服务端发送的数据
- // MessageReceived += (data) => {
- // Console.WriteLine(data);
- // };
- // //开始链接
- // Start();
- // SendMessage(SocketMsgManger.offlineMsg());
- //}
-
-
- public void StartWsClient()
- {
- string url = "ws://schoolwstest.xhkjedu.com/ws";
- 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;
-
- //注册消息接收事件,接收服务端发送的数据
- MessageReceived += (data) =>
- {
- Console.WriteLine(data);
- };
- //开始链接
- Start();
- SendMessage(SocketMsgManger.offlineMsg());
- }
- #region "web socket "
- /// <summary>
- /// 连接方法
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 消息收到事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void WebSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
- {
- _Logger.Info(" Received:" + e.Message);
- MessageReceived?.Invoke(e.Message);
-
- Console.WriteLine("WS:消息收到:" + e.Message);
-
-
- SocketModel msgBean = JsonHelper.JsonToObj<SocketModel>(e.Message);
-
- if (msgBean != null && msgBean.b != null)
- {
- if (msgBean.c != 0&& msgBean.u == 2)
- {
- if (msgBean.c == 2001)//上线
- {
- OnlineUserModel item = new OnlineUserModel
- {
- usertype = msgBean.c,
- userid = msgBean.b.stid,
- username = msgBean.b.stname,
- userpic = msgBean.b.stpic
- };
- APP.OnlineUserList.Add(item);
- sendUserChangeToWin();
- }
- else if(msgBean.c == 2002)//下线
- {
- try
- {
- for (int i = 0; i < APP.OnlineUserList.Count; i++)
- {
- if (msgBean.b.stid == APP.OnlineUserList[i].userid)
- {
- APP.OnlineUserList.RemoveAt(i);
-
- break;
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("(移除)" + ex.Message, ex);
- }
- sendUserChangeToWin();
- }
- sendMsgToWin(msgBean);
- }
- }
- }
- private static void sendMsgToWin(SocketModel msg)
- {
- foreach (KeyValuePair<Type, object> kvp in WinDic)
- {
- if (kvp.Value is SocketCallback callback)
- {
- callback.receiveWsMsg(msg);
- }
- }
- }
- /// <summary>
- /// 添加要推送消息的窗口
- /// </summary>
- /// <param name="win"></param>
- public void addWin(object win)
- {
- if (WinDic.ContainsKey(win.GetType()))
- {
- WinDic[win.GetType()] = win;
- }
- else
- {
- WinDic.Add(win.GetType(), win);
- }
- }
- /// <summary>
- /// 发送给需要接收的窗口
- /// </summary>
- private static void sendUserChangeToWin()
- {
- foreach (KeyValuePair<Type, object> kvp in WinDic)
- {
- if (kvp.Value is SocketCallback callback)
- {
- callback.userListChange();
- }
- }
- }
- /// <summary>
- /// 移除窗口
- /// </summary>
- /// <param name="win"></param>
- public void removedWin(object win)
- {
- if (WinDic.ContainsKey(win.GetType()))
- {
- WinDic.Remove(win.GetType());
- }
- }
-
-
-
-
- /// <summary>
- /// Socket关闭事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void WebSocket_Closed(object sender, EventArgs e)
- {
- _Logger.Info("websocket_Closed");
- }
- /// <summary>
- /// Socket报错事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void WebSocket_Error(object sender, ErrorEventArgs e)
- {
- _Logger.Info("websocket_Error:" + e.Exception.ToString());
- }
- /// <summary>
- /// Socket打开事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void WebSocket_Opened(object sender, EventArgs e)
- {
- SendMessage(SocketMsgManger.AddMsg());
- _Logger.Info(" websocket_Opened");
-
-
-
- SendMessage(SocketMsgManger.offlineMsg());
-
- }
- /// <summary>
- /// 检查重连线程
- /// </summary>
- 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
-
- /// <summary>
- /// 发送消息
- /// </summary>
- /// <param name="Message"></param>
- public void SendMessage(string Message)
- {
- Task.Factory.StartNew(() =>
- {
- if (_webSocket != null && _webSocket.State == WebSocket4Net.WebSocketState.Open)
- {
- this._webSocket.Send(Message);
- Console.WriteLine("WS:发送消息:" + Message);
- }
- });
- }
-
- public void Dispose()
- {
- this._isRunning = false;
- try
- {
- _thread.Abort();
- }
- catch
- {
-
- }
- this._webSocket.Close();
- this._webSocket.Dispose();
- this._webSocket = null;
- }
- }
- }
|