NotificationServer.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Net;
  4. using System.Net.WebSockets;
  5. using WingServerCommon.Log;
  6. using WingInterfaceLibrary.Enum;
  7. using WingInterfaceLibrary.Request.Authentication;
  8. using WingInterfaceLibrary.Interface;
  9. using WingNotificationModule.Channel.WebSocket;
  10. using System.Threading.Tasks;
  11. using WingNotificationModule.Adapter;
  12. using WingInterfaceLibrary.Notifications;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using WingInterfaceLibrary.Internal.Request;
  16. using WingInterfaceLibrary.Enum.NotificationEnum;
  17. namespace WingNotificationModule
  18. {
  19. internal partial class NotificationServer
  20. {
  21. private readonly ConcurrentDictionary<string, WebScoketLeaf> _leaves = new ConcurrentDictionary<string, WebScoketLeaf>();
  22. private HttpListener _httpListener;
  23. private IAuthenticationService _authenticationService;
  24. private readonly string _host;
  25. private readonly NotificationQueueManager _notifcationQueueManager;
  26. public NotificationServer(string host, int maxQueueCount)
  27. {
  28. _host = host;
  29. _notifcationQueueManager = new NotificationQueueManager(maxQueueCount, SendMessage);
  30. }
  31. /// <summary>
  32. /// Start server
  33. /// </summary>
  34. public void Start(IAuthenticationService authenticationService)
  35. {
  36. _authenticationService = authenticationService;
  37. _httpListener = new();
  38. _httpListener.Prefixes.Add(_host);
  39. _httpListener.Start();
  40. _httpListener.BeginGetContext(new AsyncCallback(GetContextCallBackAsync), _httpListener);
  41. Logger.WriteLineInfo($"{_host} is listening.");
  42. }
  43. private void GetContextCallBackAsync(IAsyncResult ar)
  44. {
  45. HttpListener listener = (HttpListener)ar.AsyncState;
  46. HttpListenerContext context = listener.EndGetContext(ar);
  47. try
  48. {
  49. listener.BeginGetContext(new AsyncCallback(GetContextCallBackAsync), listener);
  50. var token = context?.Request?.QueryString["Token"]?.ToString();
  51. var type = context?.Request?.QueryString["Type"]?.ToString();
  52. Logger.WriteLineInfo($"GetContextCallBackAsync token:{token},Type:{type}");
  53. HandleWebSocketAccept(context, token, type);
  54. }
  55. catch (Exception ex)
  56. {
  57. try
  58. {
  59. Logger.WriteLineWarn($"GetContextCallBackAsync exception:{ex}");
  60. context.Response.Abort();
  61. }
  62. catch (Exception exx)
  63. {
  64. Logger.WriteLineWarn($"context.Response.Abort() exception:{exx}");
  65. }
  66. }
  67. }
  68. async void HandleWebSocketAccept(HttpListenerContext context, string token, string type)
  69. {
  70. WebScoketLeaf leaf = null;
  71. try
  72. {
  73. WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);
  74. var webSocket = webSocketContext.WebSocket;
  75. var state = webSocket.State;
  76. //默认连接是token,其他连接是token_1,token_2...
  77. var wsToken = "";
  78. if (string.IsNullOrWhiteSpace(type) || type == "0")
  79. {
  80. wsToken = token;
  81. }
  82. else
  83. {
  84. wsToken = token + "_" + type;
  85. }
  86. if (state == WebSocketState.Open)
  87. {
  88. leaf = new WebScoketLeaf(webSocket, wsToken);
  89. //check token id valid
  90. if (string.IsNullOrEmpty(wsToken))
  91. {
  92. await leaf.SendAsync(new DisconnectNotification()
  93. {
  94. });
  95. //scoketLeaf.Close(); //TODO if need to close leaf at server ?
  96. return;
  97. }
  98. if (type != WSConnectTypeEnum.AppletAPI.ToString("D"))//小程序连接不验证token
  99. {
  100. var result = await _authenticationService.ValidateTokenAsync(new ValidateTokenRequest() { Token = token }); //TODO do we need know why the token invalid ?
  101. if (result == null || result.Code != CustomerRpcCode.Ok)
  102. {
  103. await leaf.SendAsync(new DisconnectNotification()
  104. {
  105. });
  106. return;
  107. }
  108. }
  109. //cache web socket connection
  110. _leaves.AddOrUpdate(wsToken, (t) =>
  111. {
  112. Logger.WriteLineInfo($"Websocket connection with token {wsToken} status:{state}, add leaf");
  113. return leaf;
  114. }, (t, exist) =>
  115. {
  116. Logger.WriteLineInfo($"Websocket connection with token {wsToken} status:{state}, replace leaf");
  117. exist.Close();
  118. return leaf;
  119. });
  120. await leaf.SendAsync(new ConnectionNotification());
  121. }
  122. else
  123. {
  124. Logger.WriteLineWarn($"Websocket connection with token {wsToken} status:{state}");
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. Logger.WriteLineError($"HandleWebSocketAccept with token {token} exception: {ex}");
  130. }
  131. }
  132. /// <summary>
  133. /// Send a message to client and return immediately after sending
  134. /// </summary>
  135. /// <param name="request">the message</param>
  136. /// <returns>bool</returns>
  137. /// <value>true/false</value>
  138. public async Task<bool> SendMessageAsync(SendNotificationRequest request)
  139. {
  140. var wsConnectType = request.WSConnectType;
  141. var tokens = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest() { ClientId = request.ClientId });
  142. tokens = GetDistinctTokenInfos(tokens);
  143. foreach (var token in tokens)
  144. {
  145. //如果存在第二窗口连接则使用第二窗口连接,如果没有第二窗口连接则使用主连接发送消息
  146. var wsToken = token.Code + "_" + wsConnectType.ToString("D");
  147. if (wsConnectType == WSConnectTypeEnum.ConsultationSecondWindow || wsConnectType == WSConnectTypeEnum.EducationSecondWindow || wsConnectType == WSConnectTypeEnum.AppletAPI)
  148. {
  149. if (_leaves.TryGetValue(wsToken, out var leafConsultation))
  150. {
  151. var sendResult = await leafConsultation.SendAsync(request.Message);
  152. if (sendResult)
  153. {
  154. return true;
  155. }
  156. }
  157. }
  158. else if (wsConnectType == WSConnectTypeEnum.RemoteConnectSecondWindow)
  159. {
  160. if (_leaves.TryGetValue(wsToken, out var leafRemote))
  161. {
  162. var sendResult = await leafRemote.SendAsync(request.Message);
  163. }
  164. else
  165. {
  166. wsToken = token + "_" + WSConnectTypeEnum.ConsultationSecondWindow.ToString("D");
  167. if (_leaves.TryGetValue(wsToken, out var leafConsultation))
  168. {
  169. var sendResult = leafConsultation.Send(request.Message);
  170. }
  171. }
  172. }
  173. if (_leaves.TryGetValue(token.Code, out var leaf))
  174. {
  175. await leaf.SendAsync(request.Message);
  176. return true;
  177. }
  178. else
  179. {
  180. Logger.WriteLineWarn($"Not found connection for token {token}");
  181. }
  182. }
  183. return false;
  184. }
  185. /// <summary>
  186. /// Send a message to client and return immediately after sending
  187. /// </summary>
  188. /// <param name="request">the message</param>
  189. /// <returns>bool</returns>
  190. /// <value>true/false</value>
  191. public async Task<bool> SendMessageAsync(IList<TokenDTO> tokens, SendNotificationRequest request)
  192. {
  193. var wsConnectType = request.WSConnectType;
  194. tokens = GetDistinctTokenInfos(tokens);
  195. foreach (var token in tokens)
  196. {
  197. //如果存在第二窗口连接则使用第二窗口连接,如果没有第二窗口连接则使用主连接发送消息
  198. var wsToken = token.Code + "_" + wsConnectType.ToString("D");
  199. if (wsConnectType == WSConnectTypeEnum.ConsultationSecondWindow || wsConnectType == WSConnectTypeEnum.EducationSecondWindow || wsConnectType == WSConnectTypeEnum.AppletAPI)
  200. {
  201. if (_leaves.TryGetValue(wsToken, out var leafConsultation))
  202. {
  203. var sendResult = await leafConsultation.SendAsync(request.Message);
  204. if (sendResult)
  205. {
  206. return true;
  207. }
  208. }
  209. }
  210. else if (wsConnectType == WSConnectTypeEnum.RemoteConnectSecondWindow)
  211. {
  212. if (_leaves.TryGetValue(wsToken, out var leafRemote))
  213. {
  214. var sendResult = await leafRemote.SendAsync(request.Message);
  215. }
  216. else
  217. {
  218. wsToken = token + "_" + WSConnectTypeEnum.ConsultationSecondWindow.ToString("D");
  219. if (_leaves.TryGetValue(wsToken, out var leafConsultation))
  220. {
  221. var sendResult = leafConsultation.Send(request.Message);
  222. }
  223. }
  224. }
  225. if (_leaves.TryGetValue(token.Code, out var leaf))
  226. {
  227. await leaf.SendAsync(request.Message);
  228. return true;
  229. }
  230. else
  231. {
  232. Logger.WriteLineWarn($"Not found connection for token {token}");
  233. }
  234. }
  235. return false;
  236. }
  237. /// <summary>
  238. /// Post a message to client and return immediately after add to sending queue
  239. /// </summary>
  240. /// <param name="request">the message</param>
  241. /// <returns>bool</returns>
  242. /// <value>true/false</value>
  243. public async Task<bool> PostMessageAsync(SendNotificationRequest request)
  244. {
  245. var tokens = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest() { ClientId = request.ClientId });
  246. tokens = GetDistinctTokenInfos(tokens);
  247. foreach (var token in tokens)
  248. {
  249. Logger.WriteLineInfo($"NotificationService PostMessageAsync, account name:{token.AccountName}, token: {token.Code}, wsConnectType{request.WSConnectType},message:{request.Message}");
  250. _notifcationQueueManager.Post(string.Empty, new PostMessageParam(token.Code, request.Message, request.WSConnectType));
  251. }
  252. return true;
  253. }
  254. /// <summary>
  255. /// Post a message to client and return immediately after add to sending queue
  256. /// </summary>
  257. /// <param name="request">the message</param>
  258. /// <returns>bool</returns>
  259. /// <value>true/false</value>
  260. public async Task<bool> PostMessageAsync(IList<TokenDTO> tokens, object messageData, WSConnectTypeEnum wsConnectType)
  261. {
  262. tokens = GetDistinctTokenInfos(tokens);
  263. foreach (var token in tokens)
  264. {
  265. Logger.WriteLineInfo($"NotificationService PostMessageAsync, account name:{token.AccountName}, token: {token.Code},wsConnectType{wsConnectType}, message:{messageData}");
  266. _notifcationQueueManager.Post(string.Empty, new PostMessageParam(token.Code, messageData, wsConnectType));
  267. }
  268. return true;
  269. }
  270. private bool SendMessage(PostMessageParam param)
  271. {
  272. try
  273. {
  274. Logger.WriteLineInfo($"SendMessage start, Token:{param.Token},WSConnectType:{param.WSConnectType},Message:{param.Message}");
  275. var wsConnectType = param.WSConnectType;
  276. var token = param.Token;
  277. //如果存在第二窗口连接则使用第二窗口连接,如果没有第二窗口连接则使用主连接发送消息
  278. var wsToken = token + "_" + wsConnectType.ToString("D");
  279. if (param.WSConnectType == WSConnectTypeEnum.ConsultationSecondWindow || param.WSConnectType == WSConnectTypeEnum.EducationSecondWindow || wsConnectType == WSConnectTypeEnum.AppletAPI)
  280. {
  281. if (_leaves.TryGetValue(wsToken, out var leafConsultation))
  282. {
  283. var sendResult = leafConsultation.Send(param.Message);
  284. if (sendResult)
  285. {
  286. return true;
  287. }
  288. }
  289. }
  290. else if (wsConnectType == WSConnectTypeEnum.RemoteConnectSecondWindow)
  291. {
  292. if (_leaves.TryGetValue(wsToken, out var leafRemote))
  293. {
  294. var sendResult = leafRemote.Send(param.Message);
  295. }
  296. else
  297. {
  298. wsToken = token + "_" + WSConnectTypeEnum.ConsultationSecondWindow.ToString("D");
  299. if (_leaves.TryGetValue(wsToken, out var leafConsultation))
  300. {
  301. var sendResult = leafConsultation.Send(param.Message);
  302. }
  303. }
  304. }
  305. if (_leaves.TryGetValue(token, out var leaf))
  306. {
  307. leaf.Send(param.Message);
  308. }
  309. else
  310. {
  311. Logger.WriteLineWarn($"Not found connection for token {token} when post message");
  312. }
  313. }
  314. catch (Exception ex)
  315. {
  316. Logger.WriteLineError($"post message ex:{ex}");
  317. return false;
  318. }
  319. return true;
  320. }
  321. /// <summary>
  322. /// 开启独立队列
  323. /// </summary>
  324. /// <param name="module"></param>
  325. /// <returns></returns>
  326. public string OpenNotifyQueueAsync(string module)
  327. {
  328. var msgQueueId = module + "_" + Guid.NewGuid().ToString("N").ToUpper();
  329. var openResult = _notifcationQueueManager.TryAdd(msgQueueId);
  330. return openResult ? msgQueueId : "DefaultMessageQueue";//todo 如果add失败返回什么
  331. }
  332. /// <summary>
  333. /// Post a message to clients and return immediately after add to sending queue
  334. /// </summary>
  335. /// <param name="request">the message</param>
  336. /// <returns>bool</returns>
  337. /// <value>true/false</value>
  338. public async Task<bool> BroadcastMessageAsync(BroadcastNotificationRequest request)
  339. {
  340. var tokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest() { ClientIds = request.ClientIds.ToList() });
  341. tokens = GetDistinctTokenInfos(tokens);
  342. foreach (var token in tokens)
  343. {
  344. Logger.WriteLineInfo($"NotificationService BroadcastMessageAsync, account name:{token.AccountName}, token: {token.Code}, msgQueueId:{request.MsgQueueId},wsConnectType:{request.WSConnectType}, message:{request.Message}");
  345. _notifcationQueueManager.Post(request.MsgQueueId, new PostMessageParam(token.Code, request.Message, request.WSConnectType));
  346. }
  347. return true;
  348. }
  349. /// <summary>
  350. /// Post a message to clients and return immediately after add to sending queue
  351. /// </summary>
  352. /// <param name="request">the message</param>
  353. /// <returns>bool</returns>
  354. /// <value>true/false</value>
  355. public async Task<bool> BroadcastMessageAsync(IList<TokenDTO> tokens, BroadcastNotificationRequest request)
  356. {
  357. tokens = GetDistinctTokenInfos(tokens);
  358. foreach (var token in tokens)
  359. {
  360. Logger.WriteLineInfo($"NotificationService BroadcastMessageAsync, account name:{token.AccountName}, token: {token.Code}, msgQueueId:{request.MsgQueueId},wsConnectType:{request.WSConnectType}, message:{request.Message}");
  361. _notifcationQueueManager.Post(request.MsgQueueId, new PostMessageParam(token.Code, request.Message, request.WSConnectType));
  362. }
  363. return true;
  364. }
  365. /// <summary>
  366. /// 移除websocket用户
  367. /// </summary>
  368. /// <param name="request">请求实体</param>
  369. /// <returns>true</returns>
  370. public async Task<bool> RemoveToken(string tokenCode)
  371. {
  372. var result = true;
  373. //如果存在第二窗口连接则使用第二窗口连接,如果没有第二窗口连接则使用主连接发送消息
  374. var wsConsultationToken = tokenCode + "_" + WSConnectTypeEnum.ConsultationSecondWindow.ToString("D");
  375. var wsEducationToken = tokenCode + "_" + WSConnectTypeEnum.EducationSecondWindow.ToString("D");
  376. var wsRemoteConnectToken = tokenCode + "_" + WSConnectTypeEnum.RemoteConnectSecondWindow.ToString("D");
  377. if (_leaves.ContainsKey(wsRemoteConnectToken))
  378. {
  379. result = result & _leaves.TryRemove(wsRemoteConnectToken, out _);
  380. }
  381. if (_leaves.ContainsKey(wsConsultationToken))
  382. {
  383. result = result & _leaves.TryRemove(wsConsultationToken, out _);
  384. }
  385. if (_leaves.ContainsKey(wsEducationToken))
  386. {
  387. result = result & _leaves.TryRemove(wsEducationToken, out _);
  388. }
  389. if (_leaves.ContainsKey(tokenCode))
  390. {
  391. result = result & _leaves.TryRemove(tokenCode, out _);
  392. }
  393. return await Task.FromResult(result);
  394. }
  395. /// <summary>
  396. /// 移除websocket用户
  397. /// </summary>
  398. /// <param name="request">请求实体</param>
  399. /// <returns>true</returns>
  400. public async Task<bool> RemoveSingleTokenAsync(string tokenCode)
  401. {
  402. var result = false;
  403. if (_leaves.ContainsKey(tokenCode))
  404. {
  405. result = _leaves.TryRemove(tokenCode, out _);
  406. }
  407. return await Task.FromResult(result);
  408. }
  409. /// <summary>
  410. /// 关闭独立队列
  411. /// </summary>
  412. /// <param name="module"></param>
  413. /// <returns></returns>
  414. public bool CloseNotifyQueueAsync(string queueId)
  415. {
  416. return _notifcationQueueManager.TryRemove(queueId);
  417. }
  418. /// <summary>
  419. /// Stop server
  420. /// </summary>
  421. public void Stop()
  422. {
  423. _httpListener.Stop();
  424. }
  425. private IList<TokenDTO> GetDistinctTokenInfos(IList<TokenDTO> tokenInfos)
  426. {
  427. var tokens = new List<TokenDTO>();
  428. if (tokenInfos != null && tokenInfos.Any())
  429. {
  430. var tokenCodes = tokenInfos.Select(x => x.Code).Distinct();
  431. foreach (var item in tokenCodes)
  432. {
  433. tokens.Add(tokenInfos.FirstOrDefault(x => x.Code == item));
  434. }
  435. }
  436. return tokens;
  437. }
  438. internal class PostMessageParam
  439. {
  440. /// <summary>
  441. /// The token hash code
  442. /// </summary>
  443. /// <value></value>
  444. public string Token { get; }
  445. /// <summary>
  446. /// The request message from caller
  447. /// </summary>
  448. /// <value></value>
  449. public object Message { get; }
  450. public WSConnectTypeEnum WSConnectType { get; set; }
  451. public PostMessageParam(string token, object message, WSConnectTypeEnum wsConnectType)
  452. {
  453. this.Token = token;
  454. this.Message = message;
  455. this.WSConnectType = wsConnectType;
  456. }
  457. }
  458. private class WebScoketLeaf
  459. {
  460. WebSocketIO _webSocketIO;
  461. public string ClientToken { get; }
  462. public WebScoketLeaf(WebSocket webSocket, string token)
  463. {
  464. ClientToken = token;
  465. _webSocketIO = new WebSocketIO(webSocket);
  466. }
  467. /// <summary>
  468. /// Send messge async
  469. /// </summary>
  470. /// <param name="message">The message will be send to client</param>
  471. /// <returns></returns>
  472. public async Task<bool> SendAsync(object message)
  473. {
  474. if (_webSocketIO.IsDisconnected)
  475. {
  476. Logger.WriteLineWarn($"WebSocket is closed,message:{message}");
  477. return false;
  478. }
  479. Logger.WriteLineInfo($"SendAsync start,message:{message}");
  480. var adapter = new BufferAdapter(message);
  481. var buffer = adapter.GetMessageBuffer();
  482. try
  483. {
  484. await _webSocketIO.SendAsync(buffer, WebSocketMessageType.Binary);
  485. Logger.WriteLineInfo($"SendAsync end, message:{message}");
  486. }
  487. catch (Exception ex)
  488. {
  489. Logger.WriteLineWarn($"SendAsync error,maybe sendWindows closed:ex:{ex}");
  490. return false;
  491. }
  492. return true;
  493. }
  494. /// <summary>
  495. /// Send messge
  496. /// </summary>
  497. /// <param name="message">The message will be send to client</param>
  498. /// <returns></returns>
  499. public bool Send(object message)
  500. {
  501. if (_webSocketIO.IsDisconnected)
  502. {
  503. Logger.WriteLineWarn($"WebSocket is closed,message:{message}");
  504. return false;
  505. }
  506. Logger.WriteLineInfo($"Send start, message:{message}");
  507. var adapter = new BufferAdapter(message);
  508. var buffer = adapter.GetMessageBuffer();
  509. try
  510. {
  511. _webSocketIO.Send(buffer, WebSocketMessageType.Binary);
  512. Logger.WriteLineInfo($"Send end, message:{message}");
  513. }
  514. catch (Exception ex)
  515. {
  516. Logger.WriteLineWarn($"Send error,maybe sendWindows closed:ex:{ex}");
  517. return false;
  518. }
  519. return true;
  520. }
  521. /// <summary>
  522. /// Close the web socket leaf connection
  523. /// </summary>
  524. public void Close()
  525. {
  526. _webSocketIO.Dispose();
  527. }
  528. }
  529. }
  530. }