#region License /* * WebSocketServiceHostManager.cs * * The MIT License * * Copyright (c) 2012-2013 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.Generic; using System.Linq; using System.Text; using WebSocketSharp.Net; namespace WebSocketSharp.Server { /// /// Manages the WebSocket services provided by the and /// . /// public class WebSocketServiceHostManager { #region Private Fields private volatile bool _keepClean; private Logger _logger; private Dictionary _serviceHosts; private volatile ServerState _state; private object _sync; #endregion #region Internal Constructors internal WebSocketServiceHostManager () : this (new Logger ()) { } internal WebSocketServiceHostManager (Logger logger) { _logger = logger; _keepClean = true; _serviceHosts = new Dictionary (); _state = ServerState.READY; _sync = new object (); } #endregion #region Public Properties /// /// Gets the connection count to the every WebSocket service provided by the WebSocket server. /// /// /// An that contains the connection count to the every WebSocket service. /// public int ConnectionCount { get { var count = 0; foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; count += host.ConnectionCount; } return count; } } /// /// Gets the number of the WebSocket services provided by the WebSocket server. /// /// /// An that contains the number of the WebSocket services. /// public int Count { get { lock (_sync) { return _serviceHosts.Count; } } } /// /// Gets the WebSocket service host with the specified . /// /// /// A instance that represents the WebSocket service host /// if it is successfully found; otherwise, . /// /// /// A that contains an absolute path to the WebSocket service managed by /// the WebSocket service host to get. /// public IWebSocketServiceHost this [string servicePath] { get { var msg = servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return null; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return host; } } /// /// Gets a value indicating whether the manager cleans up periodically the every inactive session /// to the WebSocket services provided by the WebSocket server. /// /// /// true if the manager cleans up periodically the every inactive session to the WebSocket /// services; otherwise, false. /// public bool KeepClean { get { return _keepClean; } internal set { lock (_sync) { if (!(value ^ _keepClean)) return; _keepClean = value; foreach (var host in _serviceHosts.Values) host.KeepClean = value; } } } /// /// Gets the collection of the WebSocket service hosts managed by the WebSocket server. /// /// /// An IEnumerable<IWebSocketServiceHost> that contains the collection of the WebSocket /// service hosts. /// public IEnumerable ServiceHosts { get { lock (_sync) { return _serviceHosts.Values.ToList (); } } } /// /// Gets the collection of every path to the WebSocket services provided by the WebSocket server. /// /// /// An IEnumerable<string> that contains the collection of every path to the WebSocket services. /// public IEnumerable ServicePaths { get { lock (_sync) { return _serviceHosts.Keys.ToList (); } } } #endregion #region Private Methods private Dictionary> broadping (byte [] data) { var result = new Dictionary> (); foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; result.Add (host.ServicePath, host.Sessions.BroadpingInternally (data)); } return result; } #endregion #region Internal Methods internal void Add (string servicePath, IWebSocketServiceHost serviceHost) { servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash (); lock (_sync) { IWebSocketServiceHost host; if (_serviceHosts.TryGetValue (servicePath, out host)) { _logger.Error ( "The WebSocket service with the specified path already exists.\npath: " + servicePath); return; } if (_state == ServerState.START) serviceHost.Sessions.Start (); _serviceHosts.Add (servicePath, serviceHost); } } internal bool Remove (string servicePath) { servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash (); IWebSocketServiceHost host; lock (_sync) { if (!_serviceHosts.TryGetValue (servicePath, out host)) { _logger.Error ( "The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } _serviceHosts.Remove (servicePath); } if (host.Sessions.State == ServerState.START) host.Sessions.Stop (((ushort) CloseStatusCode.AWAY).ToByteArray (ByteOrder.BIG)); return true; } internal void Start () { lock (_sync) { foreach (var host in _serviceHosts.Values) host.Sessions.Start (); _state = ServerState.START; } } internal void Stop () { lock (_sync) { _state = ServerState.SHUTDOWN; foreach (var host in _serviceHosts.Values) host.Sessions.Stop (); _serviceHosts.Clear (); _state = ServerState.STOP; } } internal void Stop (byte [] data) { lock (_sync) { _state = ServerState.SHUTDOWN; foreach (var host in _serviceHosts.Values) host.Sessions.Stop (data); _serviceHosts.Clear (); _state = ServerState.STOP; } } internal bool TryGetServiceHostInternally (string servicePath, out IWebSocketServiceHost serviceHost) { servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash (); lock (_sync) { return _serviceHosts.TryGetValue (servicePath, out serviceHost); } } #endregion #region Public Methods /// /// Broadcasts the specified array of to all clients of the WebSocket services /// provided by the WebSocket server. /// /// /// An array of to broadcast. /// public void Broadcast (byte [] data) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; host.Sessions.BroadcastInternally (data); } } /// /// Broadcasts the specified to all clients of the WebSocket services /// provided by the WebSocket server. /// /// /// A to broadcast. /// public void Broadcast (string data) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; host.Sessions.BroadcastInternally (data); } } /// /// Broadcasts the specified array of to all clients of the WebSocket service /// with the specified . /// /// /// true if is broadcasted; otherwise, false. /// /// /// An array of to broadcast. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public bool BroadcastTo (byte [] data, string servicePath) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } host.Sessions.BroadcastInternally (data); return true; } /// /// Broadcasts the specified to all clients of the WebSocket service /// with the specified . /// /// /// true if is broadcasted; otherwise, false. /// /// /// A to broadcast. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public bool BroadcastTo (string data, string servicePath) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } host.Sessions.BroadcastInternally (data); return true; } /// /// Sends Pings to all clients of the WebSocket services provided by the WebSocket server. /// /// /// A Dictionary<string, Dictionary<string, bool>> that contains the collection of /// service paths and pairs of session ID and value indicating whether each WebSocket service /// received a Pong from each client in a time. /// public Dictionary> Broadping () { var msg = _state.CheckIfStarted (); if (msg != null) { _logger.Error (msg); return null; } return broadping (new byte [] {}); } /// /// Sends Pings with the specified to all clients of the WebSocket services /// provided by the WebSocket server. /// /// /// A Dictionary<string, Dictionary<string, bool>> that contains the collection of /// service paths and pairs of session ID and value indicating whether each WebSocket service /// received a Pong from each client in a time. /// If is invalid, returns . /// /// /// A that contains a message to send. /// public Dictionary> Broadping (string message) { if (message == null || message.Length == 0) return Broadping (); var data = Encoding.UTF8.GetBytes (message); var msg = _state.CheckIfStarted () ?? data.CheckIfValidPingData (); if (msg != null) { _logger.Error (msg); return null; } return broadping (data); } /// /// Sends Pings to all clients of the WebSocket service with the specified . /// /// /// A Dictionary<string, bool> that contains the collection of pairs of session ID and value /// indicating whether the WebSocket service received a Pong from each client in a time. /// If the WebSocket service is not found, returns . /// /// /// A that contains an absolute path to the WebSocket service to find. /// public Dictionary BroadpingTo (string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return null; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return null; } return host.Sessions.BroadpingInternally (new byte [] {}); } /// /// Sends Pings with the specified to all clients of the WebSocket service /// with the specified . /// /// /// A Dictionary<string, bool> that contains the collection of pairs of session ID and value /// indicating whether the WebSocket service received a Pong from each client in a time. /// If the WebSocket service is not found, returns . /// /// /// A that contains a message to send. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public Dictionary BroadpingTo (string message, string servicePath) { if (message == null || message.Length == 0) return BroadpingTo (servicePath); var data = Encoding.UTF8.GetBytes (message); var msg = _state.CheckIfStarted () ?? data.CheckIfValidPingData () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return null; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return null; } return host.Sessions.BroadpingInternally (data); } /// /// Closes the session with the specified and /// . /// /// /// A that contains a session ID to find. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public void CloseSession (string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return; } host.Sessions.CloseSession (id); } /// /// Closes the session with the specified , , /// and . /// /// /// A that contains a status code indicating the reason for closure. /// /// /// A that contains the reason for closure. /// /// /// A that contains a session ID to find. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public void CloseSession (ushort code, string reason, string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return; } host.Sessions.CloseSession (code, reason, id); } /// /// Closes the session with the specified , , /// and . /// /// /// A that contains a status code indicating the reason for closure. /// /// /// A that contains the reason for closure. /// /// /// A that contains a session ID to find. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public void CloseSession (CloseStatusCode code, string reason, string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return; } host.Sessions.CloseSession (code, reason, id); } /// /// Sends a Ping to the client associated with the specified and /// . /// /// /// true if the WebSocket service with receives a Pong /// from the client in a time; otherwise, false. /// /// /// A that contains a session ID that represents the destination for the Ping. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public bool PingTo (string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } return host.Sessions.PingTo (id); } /// /// Sends a Ping with the specified to the client associated with /// the specified and . /// /// /// true if the WebSocket service with receives a Pong /// from the client in a time; otherwise, false. /// /// /// A that contains a message to send. /// /// /// A that contains a session ID that represents the destination for the Ping. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public bool PingTo (string message, string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } return host.Sessions.PingTo (message, id); } /// /// Sends a binary to the client associated with the specified /// and . /// /// /// true if is successfully sent; otherwise, false. /// /// /// An array of that contains a binary data to send. /// /// /// A that contains a session ID that represents the destination for the data. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public bool SendTo (byte [] data, string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } return host.Sessions.SendTo (data, id); } /// /// Sends a text to the client associated with the specified /// and . /// /// /// true if is successfully sent; otherwise, false. /// /// /// A that contains a text data to send. /// /// /// A that contains a session ID that represents the destination for the data. /// /// /// A that contains an absolute path to the WebSocket service to find. /// public bool SendTo (string data, string id, string servicePath) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } IWebSocketServiceHost host; if (!TryGetServiceHostInternally (servicePath, out host)) { _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return false; } return host.Sessions.SendTo (data, id); } /// /// Tries to get the WebSocket service host with the specified . /// /// /// true if the WebSocket service host is successfully found; otherwise, false. /// /// /// A that contains an absolute path to the WebSocket service managed by /// the WebSocket service host to get. /// /// /// When this method returns, a instance that represents /// the WebSocket service host if it is successfully found; otherwise, . /// This parameter is passed uninitialized. /// public bool TryGetServiceHost (string servicePath, out IWebSocketServiceHost serviceHost) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); serviceHost = null; return false; } var result = TryGetServiceHostInternally (servicePath, out serviceHost); if (!result) _logger.Error ("The WebSocket service with the specified path not found.\npath: " + servicePath); return result; } #endregion } }