WebSocketServiceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #region License
  2. /*
  3. * WebSocketServiceManager.cs
  4. *
  5. * The MIT License
  6. *
  7. * Copyright (c) 2012-2023 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;
  30. using System.Collections.Generic;
  31. namespace WebSocketSharp.Server
  32. {
  33. /// <summary>
  34. /// Provides the management function for the WebSocket services.
  35. /// </summary>
  36. /// <remarks>
  37. /// This class manages the WebSocket services provided by the
  38. /// <see cref="WebSocketServer"/> or <see cref="HttpServer"/> class.
  39. /// </remarks>
  40. public class WebSocketServiceManager
  41. {
  42. #region Private Fields
  43. private Dictionary<string, WebSocketServiceHost> _hosts;
  44. private volatile bool _keepClean;
  45. private Logger _log;
  46. private volatile ServerState _state;
  47. private object _sync;
  48. private TimeSpan _waitTime;
  49. #endregion
  50. #region Internal Constructors
  51. internal WebSocketServiceManager (Logger log)
  52. {
  53. _log = log;
  54. _hosts = new Dictionary<string, WebSocketServiceHost> ();
  55. _keepClean = true;
  56. _state = ServerState.Ready;
  57. _sync = ((ICollection) _hosts).SyncRoot;
  58. _waitTime = TimeSpan.FromSeconds (1);
  59. }
  60. #endregion
  61. #region Public Properties
  62. /// <summary>
  63. /// Gets the number of the WebSocket services.
  64. /// </summary>
  65. /// <value>
  66. /// An <see cref="int"/> that represents the number of the services.
  67. /// </value>
  68. public int Count {
  69. get {
  70. lock (_sync)
  71. return _hosts.Count;
  72. }
  73. }
  74. /// <summary>
  75. /// Gets the service host instances for the WebSocket services.
  76. /// </summary>
  77. /// <value>
  78. /// <para>
  79. /// An <c>IEnumerable&lt;WebSocketServiceHost&gt;</c> instance.
  80. /// </para>
  81. /// <para>
  82. /// It provides an enumerator which supports the iteration over
  83. /// the collection of the service host instances.
  84. /// </para>
  85. /// </value>
  86. public IEnumerable<WebSocketServiceHost> Hosts {
  87. get {
  88. lock (_sync)
  89. return _hosts.Values.ToList ();
  90. }
  91. }
  92. /// <summary>
  93. /// Gets the service host instance for a WebSocket service with
  94. /// the specified path.
  95. /// </summary>
  96. /// <value>
  97. /// <para>
  98. /// A <see cref="WebSocketServiceHost"/> instance or
  99. /// <see langword="null"/> if not found.
  100. /// </para>
  101. /// <para>
  102. /// The service host instance provides the function to access
  103. /// the information in the service.
  104. /// </para>
  105. /// </value>
  106. /// <param name="path">
  107. /// <para>
  108. /// A <see cref="string"/> that specifies an absolute path to
  109. /// the service to find.
  110. /// </para>
  111. /// <para>
  112. /// / is trimmed from the end of the string if present.
  113. /// </para>
  114. /// </param>
  115. /// <exception cref="ArgumentNullException">
  116. /// <paramref name="path"/> is <see langword="null"/>.
  117. /// </exception>
  118. /// <exception cref="ArgumentException">
  119. /// <para>
  120. /// <paramref name="path"/> is an empty string.
  121. /// </para>
  122. /// <para>
  123. /// -or-
  124. /// </para>
  125. /// <para>
  126. /// <paramref name="path"/> is not an absolute path.
  127. /// </para>
  128. /// <para>
  129. /// -or-
  130. /// </para>
  131. /// <para>
  132. /// <paramref name="path"/> includes either or both
  133. /// query and fragment components.
  134. /// </para>
  135. /// </exception>
  136. public WebSocketServiceHost this[string path] {
  137. get {
  138. if (path == null)
  139. throw new ArgumentNullException ("path");
  140. if (path.Length == 0)
  141. throw new ArgumentException ("An empty string.", "path");
  142. if (path[0] != '/') {
  143. var msg = "Not an absolute path.";
  144. throw new ArgumentException (msg, "path");
  145. }
  146. if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
  147. var msg = "It includes either or both query and fragment components.";
  148. throw new ArgumentException (msg, "path");
  149. }
  150. WebSocketServiceHost host;
  151. InternalTryGetServiceHost (path, out host);
  152. return host;
  153. }
  154. }
  155. /// <summary>
  156. /// Gets or sets a value indicating whether the inactive sessions in
  157. /// the WebSocket services are cleaned up periodically.
  158. /// </summary>
  159. /// <remarks>
  160. /// The set operation works if the current state of the server is
  161. /// Ready or Stop.
  162. /// </remarks>
  163. /// <value>
  164. /// <para>
  165. /// <c>true</c> if the inactive sessions are cleaned up every 60
  166. /// seconds; otherwise, <c>false</c>.
  167. /// </para>
  168. /// <para>
  169. /// The default value is <c>true</c>.
  170. /// </para>
  171. /// </value>
  172. public bool KeepClean {
  173. get {
  174. return _keepClean;
  175. }
  176. set {
  177. lock (_sync) {
  178. if (!canSet ())
  179. return;
  180. foreach (var host in _hosts.Values)
  181. host.KeepClean = value;
  182. _keepClean = value;
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// Gets the paths for the WebSocket services.
  188. /// </summary>
  189. /// <value>
  190. /// <para>
  191. /// An <c>IEnumerable&lt;string&gt;</c> instance.
  192. /// </para>
  193. /// <para>
  194. /// It provides an enumerator which supports the iteration over
  195. /// the collection of the paths.
  196. /// </para>
  197. /// </value>
  198. public IEnumerable<string> Paths {
  199. get {
  200. lock (_sync)
  201. return _hosts.Keys.ToList ();
  202. }
  203. }
  204. /// <summary>
  205. /// Gets or sets the time to wait for the response to the WebSocket
  206. /// Ping or Close.
  207. /// </summary>
  208. /// <remarks>
  209. /// The set operation works if the current state of the server is
  210. /// Ready or Stop.
  211. /// </remarks>
  212. /// <value>
  213. /// <para>
  214. /// A <see cref="TimeSpan"/> that represents the time to wait for
  215. /// the response.
  216. /// </para>
  217. /// <para>
  218. /// The default value is the same as 1 second.
  219. /// </para>
  220. /// </value>
  221. /// <exception cref="ArgumentOutOfRangeException">
  222. /// The value specified for a set operation is zero or less.
  223. /// </exception>
  224. public TimeSpan WaitTime {
  225. get {
  226. return _waitTime;
  227. }
  228. set {
  229. if (value <= TimeSpan.Zero) {
  230. var msg = "Zero or less.";
  231. throw new ArgumentOutOfRangeException ("value", msg);
  232. }
  233. lock (_sync) {
  234. if (!canSet ())
  235. return;
  236. foreach (var host in _hosts.Values)
  237. host.WaitTime = value;
  238. _waitTime = value;
  239. }
  240. }
  241. }
  242. #endregion
  243. #region Private Methods
  244. private bool canSet ()
  245. {
  246. return _state == ServerState.Ready || _state == ServerState.Stop;
  247. }
  248. #endregion
  249. #region Internal Methods
  250. internal bool InternalTryGetServiceHost (
  251. string path, out WebSocketServiceHost host
  252. )
  253. {
  254. path = path.TrimSlashFromEnd ();
  255. lock (_sync)
  256. return _hosts.TryGetValue (path, out host);
  257. }
  258. internal void Start ()
  259. {
  260. lock (_sync) {
  261. foreach (var host in _hosts.Values)
  262. host.Start ();
  263. _state = ServerState.Start;
  264. }
  265. }
  266. internal void Stop (ushort code, string reason)
  267. {
  268. lock (_sync) {
  269. _state = ServerState.ShuttingDown;
  270. foreach (var host in _hosts.Values)
  271. host.Stop (code, reason);
  272. _state = ServerState.Stop;
  273. }
  274. }
  275. #endregion
  276. #region Public Methods
  277. /// <summary>
  278. /// Adds a WebSocket service with the specified behavior, path,
  279. /// and initializer.
  280. /// </summary>
  281. /// <param name="path">
  282. /// <para>
  283. /// A <see cref="string"/> that specifies an absolute path to
  284. /// the service to add.
  285. /// </para>
  286. /// <para>
  287. /// / is trimmed from the end of the string if present.
  288. /// </para>
  289. /// </param>
  290. /// <param name="initializer">
  291. /// <para>
  292. /// An <see cref="T:System.Action{TBehavior}"/> delegate.
  293. /// </para>
  294. /// <para>
  295. /// The delegate invokes the method called when the service
  296. /// initializes a new session instance.
  297. /// </para>
  298. /// <para>
  299. /// <see langword="null"/> if not necessary.
  300. /// </para>
  301. /// </param>
  302. /// <typeparam name="TBehavior">
  303. /// <para>
  304. /// The type of the behavior for the service.
  305. /// </para>
  306. /// <para>
  307. /// It must inherit the <see cref="WebSocketBehavior"/> class.
  308. /// </para>
  309. /// <para>
  310. /// Also it must have a public parameterless constructor.
  311. /// </para>
  312. /// </typeparam>
  313. /// <exception cref="ArgumentNullException">
  314. /// <paramref name="path"/> is <see langword="null"/>.
  315. /// </exception>
  316. /// <exception cref="ArgumentException">
  317. /// <para>
  318. /// <paramref name="path"/> is an empty string.
  319. /// </para>
  320. /// <para>
  321. /// -or-
  322. /// </para>
  323. /// <para>
  324. /// <paramref name="path"/> is not an absolute path.
  325. /// </para>
  326. /// <para>
  327. /// -or-
  328. /// </para>
  329. /// <para>
  330. /// <paramref name="path"/> includes either or both
  331. /// query and fragment components.
  332. /// </para>
  333. /// <para>
  334. /// -or-
  335. /// </para>
  336. /// <para>
  337. /// <paramref name="path"/> is already in use.
  338. /// </para>
  339. /// </exception>
  340. public void AddService<TBehavior> (
  341. string path, Action<TBehavior> initializer
  342. )
  343. where TBehavior : WebSocketBehavior, new ()
  344. {
  345. if (path == null)
  346. throw new ArgumentNullException ("path");
  347. if (path.Length == 0)
  348. throw new ArgumentException ("An empty string.", "path");
  349. if (path[0] != '/') {
  350. var msg = "Not an absolute path.";
  351. throw new ArgumentException (msg, "path");
  352. }
  353. if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
  354. var msg = "It includes either or both query and fragment components.";
  355. throw new ArgumentException (msg, "path");
  356. }
  357. path = path.TrimSlashFromEnd ();
  358. lock (_sync) {
  359. WebSocketServiceHost host;
  360. if (_hosts.TryGetValue (path, out host)) {
  361. var msg = "It is already in use.";
  362. throw new ArgumentException (msg, "path");
  363. }
  364. host = new WebSocketServiceHost<TBehavior> (path, initializer, _log);
  365. if (!_keepClean)
  366. host.KeepClean = false;
  367. if (_waitTime != host.WaitTime)
  368. host.WaitTime = _waitTime;
  369. if (_state == ServerState.Start)
  370. host.Start ();
  371. _hosts.Add (path, host);
  372. }
  373. }
  374. /// <summary>
  375. /// Removes all WebSocket services managed by the manager.
  376. /// </summary>
  377. /// <remarks>
  378. /// Each service is stopped with close status 1001 (going away)
  379. /// if the current state of the service is Start.
  380. /// </remarks>
  381. public void Clear ()
  382. {
  383. List<WebSocketServiceHost> hosts = null;
  384. lock (_sync) {
  385. hosts = _hosts.Values.ToList ();
  386. _hosts.Clear ();
  387. }
  388. foreach (var host in hosts) {
  389. if (host.State == ServerState.Start)
  390. host.Stop (1001, String.Empty);
  391. }
  392. }
  393. /// <summary>
  394. /// Removes a WebSocket service with the specified path.
  395. /// </summary>
  396. /// <remarks>
  397. /// The service is stopped with close status 1001 (going away)
  398. /// if the current state of the service is Start.
  399. /// </remarks>
  400. /// <returns>
  401. /// <c>true</c> if the service is successfully found and removed;
  402. /// otherwise, <c>false</c>.
  403. /// </returns>
  404. /// <param name="path">
  405. /// <para>
  406. /// A <see cref="string"/> that specifies an absolute path to
  407. /// the service to remove.
  408. /// </para>
  409. /// <para>
  410. /// / is trimmed from the end of the string if present.
  411. /// </para>
  412. /// </param>
  413. /// <exception cref="ArgumentNullException">
  414. /// <paramref name="path"/> is <see langword="null"/>.
  415. /// </exception>
  416. /// <exception cref="ArgumentException">
  417. /// <para>
  418. /// <paramref name="path"/> is an empty string.
  419. /// </para>
  420. /// <para>
  421. /// -or-
  422. /// </para>
  423. /// <para>
  424. /// <paramref name="path"/> is not an absolute path.
  425. /// </para>
  426. /// <para>
  427. /// -or-
  428. /// </para>
  429. /// <para>
  430. /// <paramref name="path"/> includes either or both
  431. /// query and fragment components.
  432. /// </para>
  433. /// </exception>
  434. public bool RemoveService (string path)
  435. {
  436. if (path == null)
  437. throw new ArgumentNullException ("path");
  438. if (path.Length == 0)
  439. throw new ArgumentException ("An empty string.", "path");
  440. if (path[0] != '/') {
  441. var msg = "Not an absolute path.";
  442. throw new ArgumentException (msg, "path");
  443. }
  444. if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
  445. var msg = "It includes either or both query and fragment components.";
  446. throw new ArgumentException (msg, "path");
  447. }
  448. path = path.TrimSlashFromEnd ();
  449. WebSocketServiceHost host;
  450. lock (_sync) {
  451. if (!_hosts.TryGetValue (path, out host))
  452. return false;
  453. _hosts.Remove (path);
  454. }
  455. if (host.State == ServerState.Start)
  456. host.Stop (1001, String.Empty);
  457. return true;
  458. }
  459. /// <summary>
  460. /// Tries to get the service host instance for a WebSocket service with
  461. /// the specified path.
  462. /// </summary>
  463. /// <returns>
  464. /// <c>true</c> if the service is successfully found; otherwise,
  465. /// <c>false</c>.
  466. /// </returns>
  467. /// <param name="path">
  468. /// <para>
  469. /// A <see cref="string"/> that specifies an absolute path to
  470. /// the service to find.
  471. /// </para>
  472. /// <para>
  473. /// / is trimmed from the end of the string if present.
  474. /// </para>
  475. /// </param>
  476. /// <param name="host">
  477. /// <para>
  478. /// When this method returns, a <see cref="WebSocketServiceHost"/>
  479. /// instance or <see langword="null"/> if not found.
  480. /// </para>
  481. /// <para>
  482. /// The service host instance provides the function to access
  483. /// the information in the service.
  484. /// </para>
  485. /// </param>
  486. /// <exception cref="ArgumentNullException">
  487. /// <paramref name="path"/> is <see langword="null"/>.
  488. /// </exception>
  489. /// <exception cref="ArgumentException">
  490. /// <para>
  491. /// <paramref name="path"/> is an empty string.
  492. /// </para>
  493. /// <para>
  494. /// -or-
  495. /// </para>
  496. /// <para>
  497. /// <paramref name="path"/> is not an absolute path.
  498. /// </para>
  499. /// <para>
  500. /// -or-
  501. /// </para>
  502. /// <para>
  503. /// <paramref name="path"/> includes either or both
  504. /// query and fragment components.
  505. /// </para>
  506. /// </exception>
  507. public bool TryGetServiceHost (string path, out WebSocketServiceHost host)
  508. {
  509. if (path == null)
  510. throw new ArgumentNullException ("path");
  511. if (path.Length == 0)
  512. throw new ArgumentException ("An empty string.", "path");
  513. if (path[0] != '/') {
  514. var msg = "Not an absolute path.";
  515. throw new ArgumentException (msg, "path");
  516. }
  517. if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
  518. var msg = "It includes either or both query and fragment components.";
  519. throw new ArgumentException (msg, "path");
  520. }
  521. return InternalTryGetServiceHost (path, out host);
  522. }
  523. #endregion
  524. }
  525. }