星火直播PC
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

WSocketClient.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. {
  125. usertype = 2001,
  126. userid = getOnline.userid,
  127. username = getOnline.username,
  128. userpic = getOnline.headportrait
  129. };
  130. APP.OnlineUserList.Add(item);
  131. }
  132. //GetOnlineStudentsModel get = new GetOnlineStudentsModel();
  133. //get.b = new StulstModel();
  134. //Console.WriteLine("WS:消息收到1111:" + get);
  135. }
  136. if (msgBean.c != 0&& msgBean.u == 2)
  137. {
  138. if (msgBean.c == 2001)//上线
  139. {
  140. OnlineUserModel item = new OnlineUserModel
  141. {
  142. usertype = msgBean.c,
  143. userid = msgBean.b.stid,
  144. username = msgBean.b.stname,
  145. userpic = msgBean.b.stpic
  146. };
  147. APP.OnlineUserList.Add(item);
  148. sendUserChangeToWin();
  149. }
  150. else if(msgBean.c == 2002)//下线
  151. {
  152. try
  153. {
  154. for (int i = 0; i < APP.OnlineUserList.Count; i++)
  155. {
  156. if (msgBean.b.stid == APP.OnlineUserList[i].userid)
  157. {
  158. APP.OnlineUserList.RemoveAt(i);
  159. break;
  160. }
  161. }
  162. }
  163. catch (Exception ex)
  164. {
  165. LogHelper.WriteErrLog("(移除)" + ex.Message, ex);
  166. }
  167. sendUserChangeToWin();
  168. }
  169. sendMsgToWin(msgBean);
  170. }
  171. }
  172. }
  173. private static void sendMsgToWin(SocketModel msg)
  174. {
  175. foreach (KeyValuePair<Type, object> kvp in WinDic)
  176. {
  177. if (kvp.Value is SocketCallback callback)
  178. {
  179. callback.receiveWsMsg(msg);
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// 添加要推送消息的窗口
  185. /// </summary>
  186. /// <param name="win"></param>
  187. public void addWin(object win)
  188. {
  189. if (WinDic.ContainsKey(win.GetType()))
  190. {
  191. WinDic[win.GetType()] = win;
  192. }
  193. else
  194. {
  195. WinDic.Add(win.GetType(), win);
  196. }
  197. }
  198. /// <summary>
  199. /// 发送给需要接收的窗口
  200. /// </summary>
  201. private static void sendUserChangeToWin()
  202. {
  203. foreach (KeyValuePair<Type, object> kvp in WinDic)
  204. {
  205. if (kvp.Value is SocketCallback callback)
  206. {
  207. callback.userListChange();
  208. }
  209. }
  210. }
  211. /// <summary>
  212. /// 移除窗口
  213. /// </summary>
  214. /// <param name="win"></param>
  215. public void removedWin(object win)
  216. {
  217. if (WinDic.ContainsKey(win.GetType()))
  218. {
  219. WinDic.Remove(win.GetType());
  220. }
  221. }
  222. /// <summary>
  223. /// Socket关闭事件
  224. /// </summary>
  225. /// <param name="sender"></param>
  226. /// <param name="e"></param>
  227. void WebSocket_Closed(object sender, EventArgs e)
  228. {
  229. _Logger.Info("websocket_Closed");
  230. }
  231. /// <summary>
  232. /// Socket报错事件
  233. /// </summary>
  234. /// <param name="sender"></param>
  235. /// <param name="e"></param>
  236. void WebSocket_Error(object sender, ErrorEventArgs e)
  237. {
  238. _Logger.Info("websocket_Error:" + e.Exception.ToString());
  239. }
  240. /// <summary>
  241. /// Socket打开事件
  242. /// </summary>
  243. /// <param name="sender"></param>
  244. /// <param name="e"></param>
  245. void WebSocket_Opened(object sender, EventArgs e)
  246. {
  247. SendMessage(SocketMsgManger.AddMsg());
  248. _Logger.Info(" websocket_Opened");
  249. SendMessage(SocketMsgManger.offlineMsg());
  250. }
  251. /// <summary>
  252. /// 检查重连线程
  253. /// </summary>
  254. private void CheckConnection()
  255. {
  256. do
  257. {
  258. try
  259. {
  260. if (this._webSocket.State != WebSocket4Net.WebSocketState.Open && this._webSocket.State != WebSocket4Net.WebSocketState.Connecting)
  261. {
  262. _Logger.Info(" Reconnect websocket WebSocketState:" + this._webSocket.State);
  263. this._webSocket.Close();
  264. this._webSocket.Open();
  265. Console.WriteLine("正在重连");
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. _Logger.Error(ex.ToString());
  271. }
  272. System.Threading.Thread.Sleep(5000);
  273. } while (this._isRunning);
  274. }
  275. #endregion
  276. /// <summary>
  277. /// 发送消息
  278. /// </summary>
  279. /// <param name="Message"></param>
  280. public void SendMessage(string Message)
  281. {
  282. Task.Factory.StartNew(() =>
  283. {
  284. if (_webSocket != null && _webSocket.State == WebSocket4Net.WebSocketState.Open)
  285. {
  286. this._webSocket.Send(Message);
  287. Console.WriteLine("WS:发送消息:" + Message);
  288. }
  289. });
  290. }
  291. public void Dispose()
  292. {
  293. this._isRunning = false;
  294. try
  295. {
  296. _thread.Abort();
  297. }
  298. catch
  299. {
  300. }
  301. this._webSocket.Close();
  302. this._webSocket.Dispose();
  303. this._webSocket = null;
  304. }
  305. }
  306. }