123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608 |
- #region License
- /*
- * WebSocketServiceManager.cs
- *
- * The MIT License
- *
- * Copyright (c) 2012-2023 sta.blockhead
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
- #endregion
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace WebSocketSharp.Server
- {
- /// <summary>
- /// Provides the management function for the WebSocket services.
- /// </summary>
- /// <remarks>
- /// This class manages the WebSocket services provided by the
- /// <see cref="WebSocketServer"/> or <see cref="HttpServer"/> class.
- /// </remarks>
- public class WebSocketServiceManager
- {
- #region Private Fields
- private Dictionary<string, WebSocketServiceHost> _hosts;
- private volatile bool _keepClean;
- private Logger _log;
- private volatile ServerState _state;
- private object _sync;
- private TimeSpan _waitTime;
- #endregion
- #region Internal Constructors
- internal WebSocketServiceManager (Logger log)
- {
- _log = log;
- _hosts = new Dictionary<string, WebSocketServiceHost> ();
- _keepClean = true;
- _state = ServerState.Ready;
- _sync = ((ICollection) _hosts).SyncRoot;
- _waitTime = TimeSpan.FromSeconds (1);
- }
- #endregion
- #region Public Properties
- /// <summary>
- /// Gets the number of the WebSocket services.
- /// </summary>
- /// <value>
- /// An <see cref="int"/> that represents the number of the services.
- /// </value>
- public int Count {
- get {
- lock (_sync)
- return _hosts.Count;
- }
- }
- /// <summary>
- /// Gets the service host instances for the WebSocket services.
- /// </summary>
- /// <value>
- /// <para>
- /// An <c>IEnumerable<WebSocketServiceHost></c> instance.
- /// </para>
- /// <para>
- /// It provides an enumerator which supports the iteration over
- /// the collection of the service host instances.
- /// </para>
- /// </value>
- public IEnumerable<WebSocketServiceHost> Hosts {
- get {
- lock (_sync)
- return _hosts.Values.ToList ();
- }
- }
- /// <summary>
- /// Gets the service host instance for a WebSocket service with
- /// the specified path.
- /// </summary>
- /// <value>
- /// <para>
- /// A <see cref="WebSocketServiceHost"/> instance or
- /// <see langword="null"/> if not found.
- /// </para>
- /// <para>
- /// The service host instance provides the function to access
- /// the information in the service.
- /// </para>
- /// </value>
- /// <param name="path">
- /// <para>
- /// A <see cref="string"/> that specifies an absolute path to
- /// the service to find.
- /// </para>
- /// <para>
- /// / is trimmed from the end of the string if present.
- /// </para>
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="path"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <para>
- /// <paramref name="path"/> is an empty string.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> is not an absolute path.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> includes either or both
- /// query and fragment components.
- /// </para>
- /// </exception>
- public WebSocketServiceHost this[string path] {
- get {
- if (path == null)
- throw new ArgumentNullException ("path");
- if (path.Length == 0)
- throw new ArgumentException ("An empty string.", "path");
- if (path[0] != '/') {
- var msg = "Not an absolute path.";
- throw new ArgumentException (msg, "path");
- }
- if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
- var msg = "It includes either or both query and fragment components.";
- throw new ArgumentException (msg, "path");
- }
- WebSocketServiceHost host;
- InternalTryGetServiceHost (path, out host);
- return host;
- }
- }
- /// <summary>
- /// Gets or sets a value indicating whether the inactive sessions in
- /// the WebSocket services are cleaned up periodically.
- /// </summary>
- /// <remarks>
- /// The set operation works if the current state of the server is
- /// Ready or Stop.
- /// </remarks>
- /// <value>
- /// <para>
- /// <c>true</c> if the inactive sessions are cleaned up every 60
- /// seconds; otherwise, <c>false</c>.
- /// </para>
- /// <para>
- /// The default value is <c>true</c>.
- /// </para>
- /// </value>
- public bool KeepClean {
- get {
- return _keepClean;
- }
- set {
- lock (_sync) {
- if (!canSet ())
- return;
- foreach (var host in _hosts.Values)
- host.KeepClean = value;
- _keepClean = value;
- }
- }
- }
- /// <summary>
- /// Gets the paths for the WebSocket services.
- /// </summary>
- /// <value>
- /// <para>
- /// An <c>IEnumerable<string></c> instance.
- /// </para>
- /// <para>
- /// It provides an enumerator which supports the iteration over
- /// the collection of the paths.
- /// </para>
- /// </value>
- public IEnumerable<string> Paths {
- get {
- lock (_sync)
- return _hosts.Keys.ToList ();
- }
- }
- /// <summary>
- /// Gets or sets the time to wait for the response to the WebSocket
- /// Ping or Close.
- /// </summary>
- /// <remarks>
- /// The set operation works if the current state of the server is
- /// Ready or Stop.
- /// </remarks>
- /// <value>
- /// <para>
- /// A <see cref="TimeSpan"/> that represents the time to wait for
- /// the response.
- /// </para>
- /// <para>
- /// The default value is the same as 1 second.
- /// </para>
- /// </value>
- /// <exception cref="ArgumentOutOfRangeException">
- /// The value specified for a set operation is zero or less.
- /// </exception>
- public TimeSpan WaitTime {
- get {
- return _waitTime;
- }
- set {
- if (value <= TimeSpan.Zero) {
- var msg = "Zero or less.";
- throw new ArgumentOutOfRangeException ("value", msg);
- }
- lock (_sync) {
- if (!canSet ())
- return;
- foreach (var host in _hosts.Values)
- host.WaitTime = value;
- _waitTime = value;
- }
- }
- }
- #endregion
- #region Private Methods
- private bool canSet ()
- {
- return _state == ServerState.Ready || _state == ServerState.Stop;
- }
- #endregion
- #region Internal Methods
- internal bool InternalTryGetServiceHost (
- string path, out WebSocketServiceHost host
- )
- {
- path = path.TrimSlashFromEnd ();
- lock (_sync)
- return _hosts.TryGetValue (path, out host);
- }
- internal void Start ()
- {
- lock (_sync) {
- foreach (var host in _hosts.Values)
- host.Start ();
- _state = ServerState.Start;
- }
- }
- internal void Stop (ushort code, string reason)
- {
- lock (_sync) {
- _state = ServerState.ShuttingDown;
- foreach (var host in _hosts.Values)
- host.Stop (code, reason);
- _state = ServerState.Stop;
- }
- }
- #endregion
- #region Public Methods
- /// <summary>
- /// Adds a WebSocket service with the specified behavior, path,
- /// and initializer.
- /// </summary>
- /// <param name="path">
- /// <para>
- /// A <see cref="string"/> that specifies an absolute path to
- /// the service to add.
- /// </para>
- /// <para>
- /// / is trimmed from the end of the string if present.
- /// </para>
- /// </param>
- /// <param name="initializer">
- /// <para>
- /// An <see cref="T:System.Action{TBehavior}"/> delegate.
- /// </para>
- /// <para>
- /// The delegate invokes the method called when the service
- /// initializes a new session instance.
- /// </para>
- /// <para>
- /// <see langword="null"/> if not necessary.
- /// </para>
- /// </param>
- /// <typeparam name="TBehavior">
- /// <para>
- /// The type of the behavior for the service.
- /// </para>
- /// <para>
- /// It must inherit the <see cref="WebSocketBehavior"/> class.
- /// </para>
- /// <para>
- /// Also it must have a public parameterless constructor.
- /// </para>
- /// </typeparam>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="path"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <para>
- /// <paramref name="path"/> is an empty string.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> is not an absolute path.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> includes either or both
- /// query and fragment components.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> is already in use.
- /// </para>
- /// </exception>
- public void AddService<TBehavior> (
- string path, Action<TBehavior> initializer
- )
- where TBehavior : WebSocketBehavior, new ()
- {
- if (path == null)
- throw new ArgumentNullException ("path");
- if (path.Length == 0)
- throw new ArgumentException ("An empty string.", "path");
- if (path[0] != '/') {
- var msg = "Not an absolute path.";
- throw new ArgumentException (msg, "path");
- }
- if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
- var msg = "It includes either or both query and fragment components.";
- throw new ArgumentException (msg, "path");
- }
- path = path.TrimSlashFromEnd ();
- lock (_sync) {
- WebSocketServiceHost host;
- if (_hosts.TryGetValue (path, out host)) {
- var msg = "It is already in use.";
- throw new ArgumentException (msg, "path");
- }
- host = new WebSocketServiceHost<TBehavior> (path, initializer, _log);
- if (!_keepClean)
- host.KeepClean = false;
- if (_waitTime != host.WaitTime)
- host.WaitTime = _waitTime;
- if (_state == ServerState.Start)
- host.Start ();
- _hosts.Add (path, host);
- }
- }
- /// <summary>
- /// Removes all WebSocket services managed by the manager.
- /// </summary>
- /// <remarks>
- /// Each service is stopped with close status 1001 (going away)
- /// if the current state of the service is Start.
- /// </remarks>
- public void Clear ()
- {
- List<WebSocketServiceHost> hosts = null;
- lock (_sync) {
- hosts = _hosts.Values.ToList ();
- _hosts.Clear ();
- }
- foreach (var host in hosts) {
- if (host.State == ServerState.Start)
- host.Stop (1001, String.Empty);
- }
- }
- /// <summary>
- /// Removes a WebSocket service with the specified path.
- /// </summary>
- /// <remarks>
- /// The service is stopped with close status 1001 (going away)
- /// if the current state of the service is Start.
- /// </remarks>
- /// <returns>
- /// <c>true</c> if the service is successfully found and removed;
- /// otherwise, <c>false</c>.
- /// </returns>
- /// <param name="path">
- /// <para>
- /// A <see cref="string"/> that specifies an absolute path to
- /// the service to remove.
- /// </para>
- /// <para>
- /// / is trimmed from the end of the string if present.
- /// </para>
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="path"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <para>
- /// <paramref name="path"/> is an empty string.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> is not an absolute path.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> includes either or both
- /// query and fragment components.
- /// </para>
- /// </exception>
- public bool RemoveService (string path)
- {
- if (path == null)
- throw new ArgumentNullException ("path");
- if (path.Length == 0)
- throw new ArgumentException ("An empty string.", "path");
- if (path[0] != '/') {
- var msg = "Not an absolute path.";
- throw new ArgumentException (msg, "path");
- }
- if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
- var msg = "It includes either or both query and fragment components.";
- throw new ArgumentException (msg, "path");
- }
- path = path.TrimSlashFromEnd ();
- WebSocketServiceHost host;
- lock (_sync) {
- if (!_hosts.TryGetValue (path, out host))
- return false;
- _hosts.Remove (path);
- }
- if (host.State == ServerState.Start)
- host.Stop (1001, String.Empty);
- return true;
- }
- /// <summary>
- /// Tries to get the service host instance for a WebSocket service with
- /// the specified path.
- /// </summary>
- /// <returns>
- /// <c>true</c> if the service is successfully found; otherwise,
- /// <c>false</c>.
- /// </returns>
- /// <param name="path">
- /// <para>
- /// A <see cref="string"/> that specifies an absolute path to
- /// the service to find.
- /// </para>
- /// <para>
- /// / is trimmed from the end of the string if present.
- /// </para>
- /// </param>
- /// <param name="host">
- /// <para>
- /// When this method returns, a <see cref="WebSocketServiceHost"/>
- /// instance or <see langword="null"/> if not found.
- /// </para>
- /// <para>
- /// The service host instance provides the function to access
- /// the information in the service.
- /// </para>
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="path"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <para>
- /// <paramref name="path"/> is an empty string.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> is not an absolute path.
- /// </para>
- /// <para>
- /// -or-
- /// </para>
- /// <para>
- /// <paramref name="path"/> includes either or both
- /// query and fragment components.
- /// </para>
- /// </exception>
- public bool TryGetServiceHost (string path, out WebSocketServiceHost host)
- {
- if (path == null)
- throw new ArgumentNullException ("path");
- if (path.Length == 0)
- throw new ArgumentException ("An empty string.", "path");
- if (path[0] != '/') {
- var msg = "Not an absolute path.";
- throw new ArgumentException (msg, "path");
- }
- if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
- var msg = "It includes either or both query and fragment components.";
- throw new ArgumentException (msg, "path");
- }
- return InternalTryGetServiceHost (path, out host);
- }
- #endregion
- }
- }
|