#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.IO; using System.Linq; using System.Text; using System.Threading; 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 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 a WebSocket service host with the specified . /// /// /// A instance that represents the service host /// if the service is successfully found; otherwise, . /// /// /// A that contains an absolute path to the service to find. /// public WebSocketServiceHost this [string servicePath] { get { WebSocketServiceHost host; TryGetServiceHost (servicePath, out host); 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<WebSocketServiceHost> 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 (); } } } /// /// Gets the number of the sessions to the every WebSocket service /// provided by the WebSocket server. /// /// /// An that contains the session count of the WebSocket server. /// public int SessionCount { get { var count = 0; foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; count += host.SessionCount; } return count; } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte [] data, Action completed) { var cache = new Dictionary (); try { foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; host.Sessions.Broadcast (opcode, data, cache); } if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary (); try { foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; host.Sessions.Broadcast (opcode, stream, cache); } if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte [] data, Action completed) { WaitCallback callback = state => { broadcast (opcode, data, completed); }; ThreadPool.QueueUserWorkItem (callback); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { WaitCallback callback = state => { broadcast (opcode, stream, completed); }; ThreadPool.QueueUserWorkItem (callback); } private Dictionary> broadping (byte [] frameAsBytes, int timeOut) { var result = new Dictionary> (); foreach (var host in ServiceHosts) { if (_state != ServerState.START) break; result.Add (host.ServicePath, host.Sessions.Broadping (frameAsBytes, timeOut)); } return result; } #endregion #region Internal Methods internal void Add (string servicePath, WebSocketServiceHost serviceHost) { lock (_sync) { WebSocketServiceHost host; if (_serviceHosts.TryGetValue (servicePath, out host)) { _logger.Error ( "A 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 (); WebSocketServiceHost host; lock (_sync) { if (!_serviceHosts.TryGetValue (servicePath, out host)) { _logger.Error ( "A 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).ToByteArrayInternally (ByteOrder.BIG), true); return true; } internal void Start () { lock (_sync) { foreach (var host in _serviceHosts.Values) host.Sessions.Start (); _state = ServerState.START; } } internal void Stop (byte [] data, bool send) { lock (_sync) { _state = ServerState.SHUTDOWN; var payload = new PayloadData (data); var args = new CloseEventArgs (payload); var frameAsBytes = send ? WsFrame.CreateCloseFrame (Mask.UNMASK, payload).ToByteArray () : null; foreach (var host in _serviceHosts.Values) host.Sessions.Stop (args, frameAsBytes); _serviceHosts.Clear (); _state = ServerState.STOP; } } internal bool TryGetServiceHostInternally (string servicePath, out WebSocketServiceHost serviceHost) { servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash (); bool result; lock (_sync) { result = _serviceHosts.TryGetValue (servicePath, out serviceHost); } if (!result) _logger.Error ("A WebSocket service with the specified path not found.\npath: " + servicePath); return result; } #endregion #region Public Methods /// /// Broadcasts a binary to all clients of the WebSocket services /// provided by a WebSocket server. /// /// /// This method does not wait for the broadcast to be complete. /// /// /// An array of that contains a binary data to broadcast. /// public void Broadcast (byte [] data) { Broadcast (data, null); } /// /// Broadcasts a text to all clients of the WebSocket services /// provided by a WebSocket server. /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains a text data to broadcast. /// public void Broadcast (string data) { Broadcast (data, null); } /// /// Broadcasts a binary to all clients of the WebSocket services /// provided by a WebSocket server. /// /// /// This method does not wait for the broadcast to be complete. /// /// /// An array of that contains a binary data to broadcast. /// /// /// A delegate that references the method(s) called when /// the broadcast is complete. /// public void Broadcast (byte [] data, Action completed) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.BINARY, data, completed); else broadcastAsync (Opcode.BINARY, new MemoryStream (data), completed); } /// /// Broadcasts a text to all clients of the WebSocket services /// provided by a WebSocket server. /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains a text data to broadcast. /// /// /// A delegate that references the method(s) called when /// the broadcast is complete. /// public void Broadcast (string data, Action completed) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } var rawData = Encoding.UTF8.GetBytes (data); if (rawData.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.TEXT, rawData, completed); else broadcastAsync (Opcode.TEXT, new MemoryStream (rawData), completed); } /// /// Broadcasts a binary data from the specified to all clients /// of the WebSocket services provided by a WebSocket server. /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A object from which contains a binary data to broadcast. /// /// /// An that contains the number of bytes to broadcast. /// /// /// true if is disposed after a binary data broadcasted; /// otherwise, false. /// public void Broadcast (Stream stream, int length, bool dispose) { Broadcast (stream, length, dispose, null); } /// /// Broadcasts a binary data from the specified to all clients /// of the WebSocket services provided by a WebSocket server. /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A object from which contains a binary data to broadcast. /// /// /// An that contains the number of bytes to broadcast. /// /// /// true if is disposed after a binary data broadcasted; /// otherwise, false. /// /// /// A delegate that references the method(s) called when /// the broadcast is complete. /// public void Broadcast (Stream stream, int length, bool dispose, Action completed) { var msg = _state.CheckIfStarted () ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' must be greater than 0." : null); if (msg != null) { _logger.Error (msg); return; } Action result = data => { var readLen = data.Length; if (readLen == 0) { _logger.Error ("A data cannot be read from 'stream'."); return; } if (readLen != length) _logger.Warn (String.Format ( "A data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}", length, readLen)); if (dispose) stream.Dispose (); if (readLen <= WebSocket.FragmentLength) broadcast (Opcode.BINARY, data, completed); else broadcast (Opcode.BINARY, new MemoryStream (data), completed); }; Action exception = ex => { _logger.Fatal (ex.ToString ()); }; stream.ReadBytesAsync (length, result, exception); } /// /// Broadcasts a binary to all clients of a WebSocket service /// with the specified . /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// An array of that contains a binary data to broadcast. /// public void BroadcastTo (string servicePath, byte [] data) { BroadcastTo (servicePath, data, null); } /// /// Broadcasts a text to all clients of a WebSocket service /// with the specified . /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a text data to broadcast. /// public void BroadcastTo (string servicePath, string data) { BroadcastTo (servicePath, data, null); } /// /// Broadcasts a binary to all clients of a WebSocket service /// with the specified . /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// An array of that contains a binary data to broadcast. /// /// /// A delegate that references the method(s) called when /// the broadcast is complete. /// public void BroadcastTo (string servicePath, byte [] data, Action completed) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.Broadcast (data, completed); } /// /// Broadcasts a text to all clients of a WebSocket service /// with the specified . /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a text data to broadcast. /// /// /// A delegate that references the method(s) called when /// the broadcast is complete. /// public void BroadcastTo (string servicePath, string data, Action completed) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.Broadcast (data, completed); } /// /// Broadcasts a binary data from the specified to all clients /// of a WebSocket service with the specified . /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A object from which contains a binary data to broadcast. /// /// /// An that contains the number of bytes to broadcast. /// /// /// true if is disposed after a binary data broadcasted; /// otherwise, false. /// public void BroadcastTo (string servicePath, Stream stream, int length, bool dispose) { BroadcastTo (servicePath, stream, length, dispose, null); } /// /// Broadcasts a binary data from the specified to all clients /// of a WebSocket service with the specified . /// /// /// This method does not wait for the broadcast to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A object from which contains a binary data to broadcast. /// /// /// An that contains the number of bytes to broadcast. /// /// /// true if is disposed after a binary data broadcasted; /// otherwise, false. /// /// /// A delegate that references the method(s) called when /// the broadcast is complete. /// public void BroadcastTo ( string servicePath, Stream stream, int length, bool dispose, Action completed) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.Broadcast (stream, length, dispose, completed); } /// /// Sends Pings to all clients of the WebSocket services provided by a 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 (WsFrame.EmptyUnmaskPingData, 1000); } /// /// Sends Pings with the specified to all clients of the WebSocket /// services provided by a 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 broadcast. /// public Dictionary> Broadping (string message) { if (message == null || message.Length == 0) return Broadping (); byte [] data; var msg = _state.CheckIfStarted () ?? (data = Encoding.UTF8.GetBytes (message)).CheckIfValidPingData (); if (msg != null) { _logger.Error (msg); return null; } return broadping (WsFrame.CreatePingFrame (Mask.UNMASK, data).ToByteArray (), 1000); } /// /// Sends Pings to all clients of a 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 not found, returns . /// /// /// A that contains an absolute path to the WebSocket service to find. /// public Dictionary BroadpingTo (string servicePath) { WebSocketServiceHost host; return TryGetServiceHost (servicePath, out host) ? host.Sessions.Broadping () : null; } /// /// Sends Pings with the specified to all clients /// of a 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 not found, returns . /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a message to send. /// public Dictionary BroadpingTo (string servicePath, string message) { WebSocketServiceHost host; return TryGetServiceHost (servicePath, out host) ? host.Sessions.Broadping (message) : null; } /// /// Closes the session with the specified and /// . /// /// /// A that contains an absolute path to a WebSocket service to find. /// /// /// A that contains a session ID to find. /// public void CloseSession (string servicePath, string id) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.CloseSession (id); } /// /// Closes the session with the specified , , /// and . /// /// /// A that contains an absolute path to a WebSocket service to find. /// /// /// A that contains a session ID to find. /// /// /// A that contains a status code indicating the reason for closure. /// /// /// A that contains the reason for closure. /// public void CloseSession (string servicePath, string id, ushort code, string reason) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.CloseSession (id, code, reason); } /// /// Closes the session with the specified , , /// and . /// /// /// A that contains an absolute path to a WebSocket service to find. /// /// /// A that contains a session ID to find. /// /// /// One of the values that indicate the status codes for closure. /// /// /// A that contains the reason for closure. /// public void CloseSession (string servicePath, string id, CloseStatusCode code, string reason) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.CloseSession (id, code, reason); } /// /// 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 an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the Ping. /// public bool PingTo (string servicePath, string id) { WebSocketServiceHost host; return TryGetServiceHost (servicePath, out host) && 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 an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the Ping. /// /// /// A that contains a message to send. /// public bool PingTo (string servicePath, string id, string message) { WebSocketServiceHost host; return TryGetServiceHost (servicePath, out host) && host.Sessions.PingTo (id, message); } /// /// Sends a binary to the client associated with the specified /// and . /// /// /// This method does not wait for the send to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the data. /// /// /// An array of that contains a binary data to send. /// public void SendTo (string servicePath, string id, byte [] data) { SendTo (servicePath, id, data, null); } /// /// Sends a text to the client associated with the specified /// and . /// /// /// This method does not wait for the send to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the data. /// /// /// A that contains a text data to send. /// public void SendTo (string servicePath, string id, string data) { SendTo (servicePath, id, data, null); } /// /// Sends a binary to the client associated with the specified /// and . /// /// /// This method does not wait for the send to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the data. /// /// /// An array of that contains a binary data to send. /// /// /// An Action<bool> delegate that references the method(s) called when /// the send is complete. /// A passed to this delegate is true if the send is complete /// successfully; otherwise, false. /// public void SendTo (string servicePath, string id, byte [] data, Action completed) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.SendTo (id, data, completed); } /// /// Sends a text to the client associated with the specified /// and . /// /// /// This method does not wait for the send to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the data. /// /// /// A that contains a text data to send. /// /// /// An Action<bool> delegate that references the method(s) called when /// the send is complete. /// A passed to this delegate is true if the send is complete /// successfully; otherwise, false. /// public void SendTo (string servicePath, string id, string data, Action completed) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.SendTo (id, data, completed); } /// /// Sends a binary data from the specified to the client associated with /// the specified and . /// /// /// This method does not wait for the send to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the data. /// /// /// A object from which contains a binary data to send. /// /// /// An that contains the number of bytes to send. /// /// /// true if is disposed after a binary data read; /// otherwise, false. /// public void SendTo (string servicePath, string id, Stream stream, int length, bool dispose) { SendTo (servicePath, id, stream, length, dispose, null); } /// /// Sends a binary data from the specified to the client associated with /// the specified and . /// /// /// This method does not wait for the send to be complete. /// /// /// A that contains an absolute path to the WebSocket service to find. /// /// /// A that contains a session ID that represents the destination /// for the data. /// /// /// A object from which contains a binary data to send. /// /// /// An that contains the number of bytes to send. /// /// /// true if is disposed after a binary data read; /// otherwise, false. /// /// /// An Action<bool> delegate that references the method(s) called when /// the send is complete. /// A passed to this delegate is true if the send is complete /// successfully; otherwise, false. /// public void SendTo ( string servicePath, string id, Stream stream, int length, bool dispose, Action completed) { WebSocketServiceHost host; if (TryGetServiceHost (servicePath, out host)) host.Sessions.SendTo (id, stream, length, dispose, completed); } /// /// Tries to get a WebSocket service host with the specified . /// /// /// true if the service is successfully found; otherwise, false. /// /// /// A that contains an absolute path to the service to find. /// /// /// When this method returns, a instance that represents /// the service host if the service is successfully found; otherwise, . /// This parameter is passed uninitialized. /// public bool TryGetServiceHost (string servicePath, out WebSocketServiceHost serviceHost) { var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); serviceHost = null; return false; } return TryGetServiceHostInternally (servicePath, out serviceHost); } #endregion } }