#region License /* * WebSocketServiceManager.cs * * The MIT License * * Copyright (c) 2012-2015 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 . /// public class WebSocketServiceManager { #region Private Fields private volatile bool _clean; private Dictionary _hosts; private Logger _log; private volatile ServerState _state; private object _sync; private TimeSpan _waitTime; #endregion #region Internal Constructors internal WebSocketServiceManager (Logger log) { _log = log; _clean = true; _hosts = new Dictionary (); _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 host instances for the WebSocket services. /// /// /// /// An IEnumerable<WebSocketServiceHost> instance. /// /// /// It provides an enumerator which supports the iteration over /// the collection of the host instances. /// /// public IEnumerable Hosts { get { lock (_sync) return _hosts.Values.ToList (); } } /// /// Gets the host instance for a WebSocket service with the specified path. /// /// /// /// A instance or /// if not found. /// /// /// The host instance provides the function to access /// the information in the service. /// /// /// /// /// A that represents an absolute path to /// the service to find. /// /// /// / is trimmed from the end of the string if present. /// /// /// /// is . /// /// /// /// is empty. /// /// /// -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] != '/') throw new ArgumentException ("Not an absolute path.", "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. /// public bool KeepClean { get { return _clean; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } foreach (var host in _hosts.Values) host.KeepClean = value; _clean = 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 the total number of the sessions in the WebSocket services. /// /// /// An that represents the total number of /// the sessions in the services. /// [Obsolete ("This property will be removed.")] public int SessionCount { get { var cnt = 0; foreach (var host in Hosts) { if (_state != ServerState.Start) break; cnt += host.Sessions.Count; } return cnt; } } /// /// 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 value specified for a set operation is zero or less. /// public TimeSpan WaitTime { get { return _waitTime; } set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException ("value", "Zero or less."); string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } foreach (var host in _hosts.Values) host.WaitTime = value; _waitTime = value; } } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte[] data, Action completed) { var cache = new Dictionary (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } host.Sessions.Broadcast (opcode, data, cache); } if (completed != null) completed (); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } host.Sessions.Broadcast (opcode, stream, cache); } if (completed != null) completed (); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte[] data, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, data, completed) ); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, stream, completed) ); } private Dictionary> broadping ( byte[] frameAsBytes, TimeSpan timeout ) { var ret = new Dictionary> (); foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } var res = host.Sessions.Broadping (frameAsBytes, timeout); ret.Add (host.Path, res); } return ret; } private bool canSet (out string message) { message = null; if (_state == ServerState.Start) { message = "The server has already started."; return false; } if (_state == ServerState.ShuttingDown) { message = "The server is shutting down."; return false; } return true; } #endregion #region Internal Methods internal void Add (string path, Func creator) where TBehavior : WebSocketBehavior { path = path.TrimSlashFromEnd (); lock (_sync) { WebSocketServiceHost host; if (_hosts.TryGetValue (path, out host)) throw new ArgumentException ("Already in use.", "path"); host = new WebSocketServiceHost ( path, creator, null, _log ); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } 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 represents 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 empty. /// /// /// -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] != '/') throw new ArgumentException ("Not an absolute path.", "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)) throw new ArgumentException ("Already in use.", "path"); host = new WebSocketServiceHost ( path, () => new TBehavior (), initializer, _log ); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } /// /// Sends to every client in the WebSocket services. /// /// /// An array of that represents the binary data to send. /// /// /// The current state of the manager is not Start. /// /// /// is . /// [Obsolete ("This method will be removed.")] public void Broadcast (byte[] data) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// /// Sends to every client in the WebSocket services. /// /// /// A that represents the text data to send. /// /// /// The current state of the manager is not Start. /// /// /// is . /// /// /// could not be UTF-8-encoded. /// [Obsolete ("This method will be removed.")] public void Broadcast (string data) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); byte[] bytes; if (!data.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "data"); } if (bytes.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, bytes, null); else broadcast (Opcode.Text, new MemoryStream (bytes), null); } /// /// Sends asynchronously to every client in /// the WebSocket services. /// /// /// This method does not wait for the send to be complete. /// /// /// An array of that represents the binary data to send. /// /// /// /// An delegate or /// if not needed. /// /// /// The delegate invokes the method called when the send is complete. /// /// /// /// The current state of the manager is not Start. /// /// /// is . /// [Obsolete ("This method will be removed.")] public void BroadcastAsync (byte[] data, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, data, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (data), completed); } /// /// Sends asynchronously to every client in /// the WebSocket services. /// /// /// This method does not wait for the send to be complete. /// /// /// A that represents the text data to send. /// /// /// /// An delegate or /// if not needed. /// /// /// The delegate invokes the method called when the send is complete. /// /// /// /// The current state of the manager is not Start. /// /// /// is . /// /// /// could not be UTF-8-encoded. /// [Obsolete ("This method will be removed.")] public void BroadcastAsync (string data, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); byte[] bytes; if (!data.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "data"); } if (bytes.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Text, bytes, completed); else broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed); } /// /// Sends the data from asynchronously to /// every client in the WebSocket services. /// /// /// /// The data is sent as the binary data. /// /// /// This method does not wait for the send to be complete. /// /// /// /// A instance from which to read the data to send. /// /// /// An that specifies the number of bytes to send. /// /// /// /// An delegate or /// if not needed. /// /// /// The delegate invokes the method called when the send is complete. /// /// /// /// The current state of the manager is not Start. /// /// /// is . /// /// /// /// cannot be read. /// /// /// -or- /// /// /// is less than 1. /// /// /// -or- /// /// /// No data could be read from . /// /// [Obsolete ("This method will be removed.")] public void BroadcastAsync (Stream stream, int length, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead) { var msg = "It cannot be read."; throw new ArgumentException (msg, "stream"); } if (length < 1) { var msg = "Less than 1."; throw new ArgumentException (msg, "length"); } var bytes = stream.ReadBytes (length); var len = bytes.Length; if (len == 0) { var msg = "No data could be read from it."; throw new ArgumentException (msg, "stream"); } if (len < length) { _log.Warn ( String.Format ( "Only {0} byte(s) of data could be read from the stream.", len ) ); } if (len <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, bytes, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (bytes), completed); } /// /// Sends a ping to every client in the WebSocket services. /// /// /// /// A Dictionary<string, Dictionary<string, bool>>. /// /// /// It represents a collection of pairs of a service path and another /// collection of pairs of a session ID and a value indicating whether /// a pong has been received from the client within a time. /// /// /// /// The current state of the manager is not Start. /// [Obsolete ("This method will be removed.")] public Dictionary> Broadping () { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); } /// /// Sends a ping with to every client in /// the WebSocket services. /// /// /// /// A Dictionary<string, Dictionary<string, bool>>. /// /// /// It represents a collection of pairs of a service path and another /// collection of pairs of a session ID and a value indicating whether /// a pong has been received from the client within a time. /// /// /// /// /// A that represents the message to send. /// /// /// The size must be 125 bytes or less in UTF-8. /// /// /// /// The current state of the manager is not Start. /// /// /// could not be UTF-8-encoded. /// /// /// The size of is greater than 125 bytes. /// [Obsolete ("This method will be removed.")] public Dictionary> Broadping (string message) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (message.IsNullOrEmpty ()) return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); byte[] bytes; if (!message.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "message"); } if (bytes.Length > 125) { var msg = "Its size is greater than 125 bytes."; throw new ArgumentOutOfRangeException ("message", msg); } var frame = WebSocketFrame.CreatePingFrame (bytes, false); return broadping (frame.ToArray (), _waitTime); } /// /// 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 represents an absolute path to /// the service to remove. /// /// /// / is trimmed from the end of the string if present. /// /// /// /// is . /// /// /// /// is empty. /// /// /// -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] != '/') throw new ArgumentException ("Not an absolute path.", "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 host instance for a WebSocket service with /// the specified path. /// /// /// true if the service is successfully found; otherwise, /// false. /// /// /// /// A that represents 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 host instance provides the function to access /// the information in the service. /// /// /// /// is . /// /// /// /// is empty. /// /// /// -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] != '/') throw new ArgumentException ("Not an absolute path.", "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 } }