#region License /* * WebSocketServiceManager.cs * * The MIT License * * Copyright (c) 2012-2021 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; using System.IO; using System.Text; using System.Threading; using WebSocketSharp.Net; namespace WebSocketSharp.Server { /// /// Provides the management function for the WebSocket services. /// /// /// This class manages the WebSocket services provided by /// the or class. /// public class WebSocketServiceManager { #region Private Fields private Dictionary _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 (); _keepClean = true; _state = ServerState.Ready; _sync = ((ICollection) _hosts).SyncRoot; _waitTime = TimeSpan.FromSeconds (1); } #endregion #region Public Properties /// /// Gets the number of the WebSocket services. /// /// /// An that represents the number of the services. /// public int Count { get { lock (_sync) return _hosts.Count; } } /// /// Gets the service host instances for the WebSocket services. /// /// /// /// An IEnumerable<WebSocketServiceHost> instance. /// /// /// It provides an enumerator which supports the iteration over /// the collection of the service host instances. /// /// public IEnumerable Hosts { get { lock (_sync) return _hosts.Values.ToList (); } } /// /// Gets the service host instance for a WebSocket service with /// the specified path. /// /// /// /// A instance or /// if not found. /// /// /// The service host instance provides the function to access /// the information in the service. /// /// /// /// /// A that specifies an absolute path to /// the service to find. /// /// /// / is trimmed from the end of the string if present. /// /// /// /// is . /// /// /// /// is an empty string. /// /// /// -or- /// /// /// is not an absolute path. /// /// /// -or- /// /// /// includes either or both /// query and fragment components. /// /// 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 = "It is 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; } } /// /// Gets or sets a value indicating whether the inactive sessions in /// the WebSocket services are cleaned up periodically. /// /// /// The set operation does nothing if the server has already started or /// it is shutting down. /// /// /// /// true if the inactive sessions are cleaned up every 60 /// seconds; otherwise, false. /// /// /// The default value is true. /// /// public bool KeepClean { get { return _keepClean; } set { lock (_sync) { if (!canSet ()) return; foreach (var host in _hosts.Values) host.KeepClean = value; _keepClean = value; } } } /// /// Gets the paths for the WebSocket services. /// /// /// /// An IEnumerable<string> instance. /// /// /// It provides an enumerator which supports the iteration over /// the collection of the paths. /// /// public IEnumerable Paths { get { lock (_sync) return _hosts.Keys.ToList (); } } /// /// Gets or sets the time to wait for the response to the WebSocket Ping /// or Close. /// /// /// The set operation does nothing if the server has already started or /// it is shutting down. /// /// /// /// A to wait for the response. /// /// /// The default value is the same as 1 second. /// /// /// /// The value specified for a set operation is zero or less. /// public TimeSpan WaitTime { get { return _waitTime; } set { if (value <= TimeSpan.Zero) { var msg = "It is 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 /// /// Adds a WebSocket service with the specified behavior, path, /// and delegate. /// /// /// /// A that specifies an absolute path to /// the service to add. /// /// /// / is trimmed from the end of the string if present. /// /// /// /// /// An Action<TBehavior> delegate or /// if not needed. /// /// /// The delegate invokes the method called when initializing /// a new session instance for the service. /// /// /// /// /// The type of the behavior for the service. /// /// /// It must inherit the class. /// /// /// And also, it must have a public parameterless constructor. /// /// /// /// is . /// /// /// /// is an empty string. /// /// /// -or- /// /// /// is not an absolute path. /// /// /// -or- /// /// /// includes either or both /// query and fragment components. /// /// /// -or- /// /// /// is already in use. /// /// public void AddService ( string path, Action 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 = "It is 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 (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); } } /// /// Removes all WebSocket services managed by the manager. /// /// /// A service is stopped with close status 1001 (going away) /// if it has already started. /// public void Clear () { List 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); } } /// /// Removes a WebSocket service with the specified path. /// /// /// The service is stopped with close status 1001 (going away) /// if it has already started. /// /// /// true if the service is successfully found and removed; /// otherwise, false. /// /// /// /// A that specifies an absolute path to /// the service to remove. /// /// /// / is trimmed from the end of the string if present. /// /// /// /// is . /// /// /// /// is an empty string. /// /// /// -or- /// /// /// is not an absolute path. /// /// /// -or- /// /// /// includes either or both /// query and fragment components. /// /// 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 = "It is 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; } /// /// Tries to get the service host instance for a WebSocket service with /// the specified path. /// /// /// true if the service is successfully found; otherwise, /// false. /// /// /// /// A that specifies an absolute path to /// the service to find. /// /// /// / is trimmed from the end of the string if present. /// /// /// /// /// When this method returns, a /// instance or if not found. /// /// /// The service host instance provides the function to access /// the information in the service. /// /// /// /// is . /// /// /// /// is an empty string. /// /// /// -or- /// /// /// is not an absolute path. /// /// /// -or- /// /// /// includes either or both /// query and fragment components. /// /// 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 = "It is 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 } }