星火直播PC
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WSocketClient.cs 11KB

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