SessionManager.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #region MIT License
  2. /**
  3. * SessionManager.cs
  4. *
  5. * The MIT License
  6. *
  7. * Copyright (c) 2012 sta.blockhead
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #endregion
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Timers;
  31. using WebSocketSharp.Frame;
  32. namespace WebSocketSharp.Server
  33. {
  34. public class SessionManager
  35. {
  36. #region Private Fields
  37. private object _forSweep;
  38. private volatile bool _isStopped;
  39. private volatile bool _isSweeping;
  40. private Dictionary<string, WebSocketService> _sessions;
  41. private Timer _sweepTimer;
  42. private object _syncRoot;
  43. #endregion
  44. #region Public Constructor
  45. public SessionManager()
  46. {
  47. _forSweep = new object();
  48. _isStopped = false;
  49. _isSweeping = false;
  50. _sessions = new Dictionary<string, WebSocketService>();
  51. _sweepTimer = new Timer(60 * 1000);
  52. _sweepTimer.Elapsed += (sender, e) =>
  53. {
  54. Sweep();
  55. };
  56. _syncRoot = new object();
  57. startSweepTimer();
  58. }
  59. #endregion
  60. #region Properties
  61. public IEnumerable<string> ActiveID
  62. {
  63. get
  64. {
  65. var dict = Broadping(String.Empty);
  66. List<string> keys = new List<string>();
  67. foreach (var i in dict)
  68. if (i.Value)
  69. keys.Add(i.Key);
  70. return keys;
  71. }
  72. }
  73. public int Count
  74. {
  75. get
  76. {
  77. lock (_syncRoot)
  78. {
  79. return _sessions.Count;
  80. }
  81. }
  82. }
  83. public IEnumerable<string> InactiveID
  84. {
  85. get
  86. {
  87. var dict = Broadping(String.Empty);
  88. List<string> keys = new List<string>();
  89. foreach (var i in dict)
  90. if (!i.Value)
  91. keys.Add(i.Key);
  92. return keys;
  93. }
  94. }
  95. public IEnumerable<string> ID
  96. {
  97. get
  98. {
  99. lock (_syncRoot)
  100. {
  101. return _sessions.Keys;
  102. }
  103. }
  104. }
  105. public bool Sweeped
  106. {
  107. get
  108. {
  109. return _sweepTimer.Enabled;
  110. }
  111. set
  112. {
  113. if (value && !_isStopped)
  114. startSweepTimer();
  115. if (!value)
  116. stopSweepTimer();
  117. }
  118. }
  119. public object SyncRoot
  120. {
  121. get
  122. {
  123. return _syncRoot;
  124. }
  125. }
  126. #endregion
  127. #region Private Methods
  128. private void broadcast(byte[] data)
  129. {
  130. lock (_syncRoot)
  131. {
  132. foreach (var service in _sessions.Values)
  133. service.Send(data);
  134. }
  135. }
  136. private void broadcast(string data)
  137. {
  138. lock (_syncRoot)
  139. {
  140. foreach (var service in _sessions.Values)
  141. service.Send(data);
  142. }
  143. }
  144. private void broadcastAsync(byte[] data)
  145. {
  146. var sessions = copySessions();
  147. var services = sessions.Values.GetEnumerator();
  148. Action completed = null;
  149. completed = () =>
  150. {
  151. if (services.MoveNext())
  152. services.Current.SendAsync(data, completed);
  153. };
  154. if (services.MoveNext())
  155. services.Current.SendAsync(data, completed);
  156. }
  157. private void broadcastAsync(string data)
  158. {
  159. var sessions = copySessions();
  160. var services = sessions.Values.GetEnumerator();
  161. Action completed = null;
  162. completed = () =>
  163. {
  164. if (services.MoveNext())
  165. services.Current.SendAsync(data, completed);
  166. };
  167. if (services.MoveNext())
  168. services.Current.SendAsync(data, completed);
  169. }
  170. private Dictionary<string, WebSocketService> copySessions()
  171. {
  172. lock (_syncRoot)
  173. {
  174. return new Dictionary<string, WebSocketService>(_sessions);
  175. }
  176. }
  177. private string createID()
  178. {
  179. return Guid.NewGuid().ToString("N");
  180. }
  181. private void startSweepTimer()
  182. {
  183. if (!Sweeped)
  184. _sweepTimer.Start();
  185. }
  186. private void stopSweepTimer()
  187. {
  188. if (Sweeped)
  189. _sweepTimer.Stop();
  190. }
  191. #endregion
  192. #region Public Methods
  193. public string Add(WebSocketService service)
  194. {
  195. lock (_syncRoot)
  196. {
  197. if (_isStopped)
  198. return null;
  199. var id = createID();
  200. _sessions.Add(id, service);
  201. return id;
  202. }
  203. }
  204. public void Broadcast(byte[] data)
  205. {
  206. if (_isStopped)
  207. broadcast(data);
  208. else
  209. broadcastAsync(data);
  210. }
  211. public void Broadcast(string data)
  212. {
  213. if (_isStopped)
  214. broadcast(data);
  215. else
  216. broadcastAsync(data);
  217. }
  218. public Dictionary<string, bool> Broadping(string message)
  219. {
  220. var result = new Dictionary<string, bool>();
  221. foreach (var session in copySessions())
  222. result.Add(session.Key, session.Value.Ping(message));
  223. return result;
  224. }
  225. public bool Remove(string id)
  226. {
  227. lock (_syncRoot)
  228. {
  229. return _sessions.Remove(id);
  230. }
  231. }
  232. public bool TryGetByID(string id, out WebSocketService service)
  233. {
  234. lock (_syncRoot)
  235. {
  236. return _sessions.TryGetValue(id, out service);
  237. }
  238. }
  239. public void Stop()
  240. {
  241. Stop(CloseStatusCode.NORMAL, String.Empty);
  242. }
  243. public void Stop(CloseStatusCode code, string reason)
  244. {
  245. stopSweepTimer();
  246. lock (_syncRoot)
  247. {
  248. if (_isStopped)
  249. return;
  250. _isStopped = true;
  251. foreach (var service in copySessions().Values)
  252. service.Stop(code, reason);
  253. }
  254. }
  255. public void Sweep()
  256. {
  257. if (_isStopped || _isSweeping || Count == 0)
  258. return;
  259. lock (_forSweep)
  260. {
  261. _isSweeping = true;
  262. foreach (var id in InactiveID)
  263. {
  264. lock (_syncRoot)
  265. {
  266. if (_isStopped)
  267. {
  268. _isSweeping = false;
  269. return;
  270. }
  271. WebSocketService service;
  272. if (TryGetByID(id, out service))
  273. service.Stop(CloseStatusCode.ABNORMAL, String.Empty);
  274. }
  275. }
  276. _isSweeping = false;
  277. }
  278. }
  279. #endregion
  280. }
  281. }