星火直播PC
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

WSocketClient.cs 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using Common.system;
  2. using SuperSocket.ClientEngine;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using WebSocket4Net;
  8. using XHZB.Model;
  9. namespace XHZB.Desktop.WebSocket
  10. {
  11. public class WSocketClient : IDisposable
  12. {
  13. // 打开的窗口列表
  14. private static readonly Dictionary<Type, object> WinDic = new Dictionary<Type, object>();
  15. private static WSocketClient instance;
  16. public static WSocketClient getInstance()
  17. {
  18. if (instance == null)
  19. {
  20. instance = new WSocketClient();
  21. }
  22. return instance;
  23. }
  24. public static NLog.Logger _Logger = NLog.LogManager.GetCurrentClassLogger();
  25. #region 向外传递数据事件
  26. public event Action<string> MessageReceived;
  27. #endregion
  28. WebSocket4Net.WebSocket _webSocket;
  29. /// <summary>
  30. /// 检查重连线程
  31. /// </summary>
  32. Thread _thread;
  33. bool _isRunning = true;
  34. /// <summary>
  35. /// WebSocket连接地址
  36. /// </summary>
  37. public string ServerPath { get; set; }
  38. //public WSocketClient()
  39. //{
  40. // string url = "ws://schoolwstest.xhkjedu.com/ws";
  41. // ServerPath = url;
  42. // this._webSocket = new WebSocket4Net.WebSocket(url);
  43. // this._webSocket.Opened += WebSocket_Opened;
  44. // this._webSocket.Error += WebSocket_Error;
  45. // this._webSocket.Closed += WebSocket_Closed;
  46. // this._webSocket.MessageReceived += WebSocket_MessageReceived;
  47. // //注册消息接收事件,接收服务端发送的数据
  48. // MessageReceived += (data) => {
  49. // Console.WriteLine(data);
  50. // };
  51. // //开始链接
  52. // Start();
  53. // SendMessage(SocketMsgManger.offlineMsg());
  54. //}
  55. public void StartWsClient()
  56. {
  57. string url = "ws://schoolwstest.xhkjedu.com/ws";
  58. ServerPath = url;
  59. this._webSocket = new WebSocket4Net.WebSocket(url);
  60. this._webSocket.Opened += WebSocket_Opened;
  61. this._webSocket.Error += WebSocket_Error;
  62. this._webSocket.Closed += WebSocket_Closed;
  63. this._webSocket.MessageReceived += WebSocket_MessageReceived;
  64. //注册消息接收事件,接收服务端发送的数据
  65. MessageReceived += (data) =>
  66. {
  67. Console.WriteLine(data);
  68. };
  69. //开始链接
  70. Start();
  71. SendMessage(SocketMsgManger.offlineMsg());
  72. }
  73. #region "web socket "
  74. /// <summary>
  75. /// 连接方法
  76. /// <returns></returns>
  77. public bool Start()
  78. {
  79. bool result = true;
  80. try
  81. {
  82. this._webSocket.Open();
  83. this._isRunning = true;
  84. this._thread = new Thread(new ThreadStart(CheckConnection));
  85. this._thread.Start();
  86. }
  87. catch (Exception ex)
  88. {
  89. _Logger.Error(ex.ToString());
  90. result = false;
  91. }
  92. return result;
  93. }
  94. /// <summary>
  95. /// 消息收到事件
  96. /// </summary>
  97. /// <param name="sender"></param>
  98. /// <param name="e"></param>
  99. void WebSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
  100. {
  101. _Logger.Info(" Received:" + e.Message);
  102. MessageReceived?.Invoke(e.Message);
  103. Console.WriteLine("WS:消息收到:" + e.Message);
  104. SocketModel msgBean = JsonHelper.JsonToObj<SocketModel>(e.Message);
  105. if (msgBean != null && msgBean.b != null)
  106. {
  107. if (msgBean.c != 0&& msgBean.u == 2)
  108. {
  109. if (msgBean.c == 2001)//上线
  110. {
  111. OnlineUserModel item = new OnlineUserModel
  112. {
  113. usertype = msgBean.c,
  114. userid = msgBean.b.stid,
  115. username = msgBean.b.stname,
  116. userpic = msgBean.b.stpic
  117. };
  118. APP.OnlineUserList.Add(item);
  119. sendUserChangeToWin();
  120. }
  121. else if(msgBean.c == 2002)//下线
  122. {
  123. try
  124. {
  125. for (int i = 0; i < APP.OnlineUserList.Count; i++)
  126. {
  127. if (msgBean.b.stid == APP.OnlineUserList[i].userid)
  128. {
  129. APP.OnlineUserList.RemoveAt(i);
  130. break;
  131. }
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. LogHelper.WriteErrLog("(移除)" + ex.Message, ex);
  137. }
  138. sendUserChangeToWin();
  139. }
  140. sendMsgToWin(msgBean);
  141. }
  142. }
  143. }
  144. private static void sendMsgToWin(SocketModel msg)
  145. {
  146. foreach (KeyValuePair<Type, object> kvp in WinDic)
  147. {
  148. if (kvp.Value is SocketCallback callback)
  149. {
  150. callback.receiveWsMsg(msg);
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// 添加要推送消息的窗口
  156. /// </summary>
  157. /// <param name="win"></param>
  158. public void addWin(object win)
  159. {
  160. if (WinDic.ContainsKey(win.GetType()))
  161. {
  162. WinDic[win.GetType()] = win;
  163. }
  164. else
  165. {
  166. WinDic.Add(win.GetType(), win);
  167. }
  168. }
  169. /// <summary>
  170. /// 发送给需要接收的窗口
  171. /// </summary>
  172. private static void sendUserChangeToWin()
  173. {
  174. foreach (KeyValuePair<Type, object> kvp in WinDic)
  175. {
  176. if (kvp.Value is SocketCallback callback)
  177. {
  178. callback.userListChange();
  179. }
  180. }
  181. }
  182. /// <summary>
  183. /// 移除窗口
  184. /// </summary>
  185. /// <param name="win"></param>
  186. public void removedWin(object win)
  187. {
  188. if (WinDic.ContainsKey(win.GetType()))
  189. {
  190. WinDic.Remove(win.GetType());
  191. }
  192. }
  193. /// <summary>
  194. /// Socket关闭事件
  195. /// </summary>
  196. /// <param name="sender"></param>
  197. /// <param name="e"></param>
  198. void WebSocket_Closed(object sender, EventArgs e)
  199. {
  200. _Logger.Info("websocket_Closed");
  201. }
  202. /// <summary>
  203. /// Socket报错事件
  204. /// </summary>
  205. /// <param name="sender"></param>
  206. /// <param name="e"></param>
  207. void WebSocket_Error(object sender, ErrorEventArgs e)
  208. {
  209. _Logger.Info("websocket_Error:" + e.Exception.ToString());
  210. }
  211. /// <summary>
  212. /// Socket打开事件
  213. /// </summary>
  214. /// <param name="sender"></param>
  215. /// <param name="e"></param>
  216. void WebSocket_Opened(object sender, EventArgs e)
  217. {
  218. SendMessage(SocketMsgManger.AddMsg());
  219. _Logger.Info(" websocket_Opened");
  220. SendMessage(SocketMsgManger.offlineMsg());
  221. }
  222. /// <summary>
  223. /// 检查重连线程
  224. /// </summary>
  225. private void CheckConnection()
  226. {
  227. do
  228. {
  229. try
  230. {
  231. if (this._webSocket.State != WebSocket4Net.WebSocketState.Open && this._webSocket.State != WebSocket4Net.WebSocketState.Connecting)
  232. {
  233. _Logger.Info(" Reconnect websocket WebSocketState:" + this._webSocket.State);
  234. this._webSocket.Close();
  235. this._webSocket.Open();
  236. Console.WriteLine("正在重连");
  237. }
  238. }
  239. catch (Exception ex)
  240. {
  241. _Logger.Error(ex.ToString());
  242. }
  243. System.Threading.Thread.Sleep(5000);
  244. } while (this._isRunning);
  245. }
  246. #endregion
  247. /// <summary>
  248. /// 发送消息
  249. /// </summary>
  250. /// <param name="Message"></param>
  251. public void SendMessage(string Message)
  252. {
  253. Task.Factory.StartNew(() =>
  254. {
  255. if (_webSocket != null && _webSocket.State == WebSocket4Net.WebSocketState.Open)
  256. {
  257. this._webSocket.Send(Message);
  258. Console.WriteLine("WS:发送消息:" + Message);
  259. }
  260. });
  261. }
  262. public void Dispose()
  263. {
  264. this._isRunning = false;
  265. try
  266. {
  267. _thread.Abort();
  268. }
  269. catch
  270. {
  271. }
  272. this._webSocket.Close();
  273. this._webSocket.Dispose();
  274. this._webSocket = null;
  275. }
  276. }
  277. }