#region License /* * WebSocketSessionManager.cs * * The MIT License * * Copyright (c) 2012-2014 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.Text; using System.Threading; using System.Timers; namespace WebSocketSharp.Server { /// /// Manages the sessions in a Websocket service. /// public class WebSocketSessionManager { #region Private Static Fields private static readonly Dictionary _emptySessions; #endregion #region Private Fields private object _forSweep; private volatile bool _keepClean; private Logger _logger; private Dictionary _sessions; private volatile ServerState _state; private volatile bool _sweeping; private System.Timers.Timer _sweepTimer; private object _sync; #endregion #region Static Constructor static WebSocketSessionManager () { _emptySessions = new Dictionary (); } #endregion #region Internal Constructors internal WebSocketSessionManager () : this (new Logger ()) { } internal WebSocketSessionManager (Logger logger) { _logger = logger; _forSweep = new object (); _keepClean = true; _sessions = new Dictionary (); _state = ServerState.Ready; _sync = new object (); setSweepTimer (60000); } #endregion #region Internal Properties internal ServerState State { get { return _state; } } #endregion #region Public Properties /// /// Gets the collection of every ID of the active sessions in the Websocket service. /// /// /// An IEnumerable<string> that contains the collection of every ID of the active /// sessions. /// public IEnumerable ActiveIDs { get { foreach (var result in Broadping (WsFrame.EmptyUnmaskPingData, 1000)) if (result.Value) yield return result.Key; } } /// /// Gets the number of the sessions in the Websocket service. /// /// /// An that represents the number of the sessions. /// public int Count { get { lock (_sync) { return _sessions.Count; } } } /// /// Gets the collection of every ID of the sessions in the Websocket service. /// /// /// An IEnumerable<string> that contains the collection of every ID of the sessions. /// public IEnumerable IDs { get { if (_state == ServerState.ShuttingDown) return _emptySessions.Keys; lock (_sync) { return _sessions.Keys.ToList (); } } } /// /// Gets the collection of every ID of the inactive sessions in the Websocket service. /// /// /// An IEnumerable<string> that contains the collection of every ID of the inactive /// sessions. /// public IEnumerable InactiveIDs { get { foreach (var result in Broadping (WsFrame.EmptyUnmaskPingData, 1000)) if (!result.Value) yield return result.Key; } } /// /// Gets the information in a session with the specified in the WebSocket /// service. /// /// /// A instance that provides the access to the session if it's /// successfully found; otherwise, . /// /// /// A that represents the ID of the session to find. /// public IWebSocketSession this [string id] { get { IWebSocketSession session; TryGetSession (id, out session); return session; } } /// /// Gets a value indicating whether the manager cleans up the inactive sessions periodically. /// /// /// true if the manager cleans up the inactive sessions every 60 seconds; otherwise, /// false. /// public bool KeepClean { get { return _keepClean; } internal set { if (!(value ^ _keepClean)) return; _keepClean = value; if (_state == ServerState.Start) _sweepTimer.Enabled = value; } } /// /// Gets the collection of every information in the sessions in the Websocket service. /// /// /// An IEnumerable<IWebSocketSession> that contains the collection of every information /// in the sessions. /// public IEnumerable Sessions { get { if (_state == ServerState.ShuttingDown) return _emptySessions.Values; lock (_sync) { return _sessions.Values.ToList (); } } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte [] data, Action completed) { var cache = new Dictionary (); try { 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 { 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) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, data, completed)); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, stream, completed)); } private static string createID () { return Guid.NewGuid ().ToString ("N"); } private void setSweepTimer (double interval) { _sweepTimer = new System.Timers.Timer (interval); _sweepTimer.Elapsed += (sender, e) => Sweep (); } private bool tryGetSession (string id, out IWebSocketSession session) { bool result; lock (_sync) { result = _sessions.TryGetValue (id, out session); } if (!result) _logger.Error ("A session with the specified ID not found.\nID: " + id); return result; } #endregion #region Internal Methods internal string Add (IWebSocketSession session) { lock (_sync) { if (_state != ServerState.Start) return null; var id = createID (); _sessions.Add (id, session); return id; } } internal void Broadcast ( Opcode opcode, byte [] data, Dictionary cache) { foreach (var session in Sessions) { if (_state != ServerState.Start) break; session.Context.WebSocket.Send (opcode, data, cache); } } internal void Broadcast ( Opcode opcode, Stream stream, Dictionary cache) { foreach (var session in Sessions) { if (_state != ServerState.Start) break; session.Context.WebSocket.Send (opcode, stream, cache); } } internal Dictionary Broadping (byte [] frame, int millisecondsTimeout) { var result = new Dictionary (); foreach (var session in Sessions) { if (_state != ServerState.Start) break; result.Add ( session.ID, session.Context.WebSocket.Ping (frame, millisecondsTimeout)); } return result; } internal bool Remove (string id) { lock (_sync) { return _sessions.Remove (id); } } internal void Start () { _sweepTimer.Enabled = _keepClean; _state = ServerState.Start; } internal void Stop (byte [] data, bool send) { var payload = new PayloadData (data); var args = new CloseEventArgs (payload); var frameAsBytes = send ? WsFrame.CreateCloseFrame (Mask.Unmask, payload).ToByteArray () : null; Stop (args, frameAsBytes); } internal void Stop (CloseEventArgs args, byte [] frame) { lock (_sync) { _state = ServerState.ShuttingDown; _sweepTimer.Enabled = false; foreach (var session in _sessions.Values.ToList ()) session.Context.WebSocket.Close (args, frame, 1000); _state = ServerState.Stop; } } #endregion #region Public Methods /// /// Broadcasts a binary to every client in the WebSocket service. /// /// /// An array of that represents the binary data to broadcast. /// public void Broadcast (byte [] data) { var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// /// Broadcasts a text to every client in the WebSocket service. /// /// /// A that represents the text data to broadcast. /// public void Broadcast (string data) { var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } var rawData = Encoding.UTF8.GetBytes (data); if (rawData.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, rawData, null); else broadcast (Opcode.Text, new MemoryStream (rawData), null); } /// /// Broadcasts a binary asynchronously to every client in the WebSocket /// service. /// /// /// This method doesn't wait for the broadcast to be complete. /// /// /// An array of that represents the binary data to broadcast. /// /// /// A delegate that references the method(s) called when the broadcast is /// complete. /// public void BroadcastAsync (byte [] data, Action completed) { var msg = _state.CheckIfStart () ?? 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 asynchronously to every client in the WebSocket /// service. /// /// /// This method doesn't wait for the broadcast to be complete. /// /// /// A that represents the text data to broadcast. /// /// /// A delegate that references the method(s) called when the broadcast is /// complete. /// public void BroadcastAsync (string data, Action completed) { var msg = _state.CheckIfStart () ?? 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 asynchronously to every /// client in the WebSocket service. /// /// /// This method doesn't wait for the broadcast to be complete. /// /// /// A from which contains the binary data to broadcast. /// /// /// An that represents the number of bytes to broadcast. /// /// /// A delegate that references the method(s) called when the broadcast is /// complete. /// public void BroadcastAsync (Stream stream, int length, Action completed) { var msg = _state.CheckIfStart () ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' must be greater than 0." : null); if (msg != null) { _logger.Error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("A data cannot be read from 'stream'."); return; } if (len < length) _logger.Warn ( String.Format ( "A data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}", length, len)); if (len <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, completed); else broadcast (Opcode.Binary, new MemoryStream (data), completed); }, ex => _logger.Fatal (ex.ToString ())); } /// /// Sends a Ping to every client in the WebSocket service. /// /// /// A Dictionary<string, bool> that contains the collection of pairs of session ID and /// value indicating whether the manager received a Pong from every client in a time. /// public Dictionary Broadping () { var msg = _state.CheckIfStart (); if (msg != null) { _logger.Error (msg); return null; } return Broadping (WsFrame.EmptyUnmaskPingData, 1000); } /// /// Sends a Ping with the specified to every client in the WebSocket /// service. /// /// /// A Dictionary<string, bool> that contains the collection of pairs of session ID and /// value indicating whether the manager received a Pong from every client in a time. /// /// /// A that represents the message to send. /// public Dictionary Broadping (string message) { if (message == null || message.Length == 0) return Broadping (); byte [] data = null; var msg = _state.CheckIfStart () ?? (data = Encoding.UTF8.GetBytes (message)).CheckIfValidControlData ("message"); if (msg != null) { _logger.Error (msg); return null; } return Broadping ( WsFrame.CreatePingFrame (Mask.Unmask, data).ToByteArray (), 1000); } /// /// Closes the session with the specified . /// /// /// A that represents the ID of the session to close. /// public void CloseSession (string id) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (); } /// /// Closes the session with the specified , , and /// . /// /// /// A that represents the ID of the session to close. /// /// /// A that represents the status code indicating the reason for closure. /// /// /// A that represents the reason for closure. /// public void CloseSession (string id, ushort code, string reason) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (code, reason); } /// /// Closes the session with the specified , , and /// . /// /// /// A that represents the ID of the session to close. /// /// /// One of the enum values, represents the status code indicating /// the reason for closure. /// /// /// A that represents the reason for closure. /// public void CloseSession (string id, CloseStatusCode code, string reason) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (code, reason); } /// /// Sends a Ping to the client on the session with the specified . /// /// /// true if the manager receives a Pong from the client in a time; otherwise, /// false. /// /// /// A that represents the ID of the session to find. /// public bool PingTo (string id) { IWebSocketSession session; return TryGetSession (id, out session) && session.Context.WebSocket.Ping (); } /// /// Sends a Ping with the specified to the client on the session /// with the specified . /// /// /// true if the manager receives a Pong from the client in a time; otherwise, /// false. /// /// /// A that represents the ID of the session to find. /// /// /// A that represents the message to send. /// public bool PingTo (string id, string message) { IWebSocketSession session; return TryGetSession (id, out session) && session.Context.WebSocket.Ping (message); } /// /// Sends a binary to the client on the session with the specified /// . /// /// /// A that represents the ID of the session to find. /// /// /// An array of that represents the binary data to send. /// public void SendTo (string id, byte [] data) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Send (data); } /// /// Sends a text to the client on the session with the specified /// . /// /// /// A that represents the ID of the session to find. /// /// /// A that represents the text data to send. /// public void SendTo (string id, string data) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Send (data); } /// /// Sends a binary asynchronously to the client on the session with the /// specified . /// /// /// This method doesn't wait for the send to be complete. /// /// /// A that represents the ID of the session to find. /// /// /// An array of that represents the 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 SendToAsync (string id, byte [] data, Action completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (data, completed); } /// /// Sends a text asynchronously to the client on the session with the /// specified . /// /// /// This method doesn't wait for the send to be complete. /// /// /// A that represents the ID of the session to find. /// /// /// A that represents the 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 SendToAsync (string id, string data, Action completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (data, completed); } /// /// Sends a binary data from the specified asynchronously to the client on /// the session with the specified . /// /// /// This method doesn't wait for the send to be complete. /// /// /// A that represents the ID of the session to find. /// /// /// A from which contains the binary data to send. /// /// /// An that represents the number of bytes 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 SendToAsync ( string id, Stream stream, int length, Action completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (stream, length, completed); } /// /// Cleans up the inactive sessions in the WebSocket service. /// public void Sweep () { if (_state != ServerState.Start || _sweeping || Count == 0) return; lock (_forSweep) { _sweeping = true; foreach (var id in InactiveIDs) { if (_state != ServerState.Start) break; lock (_sync) { IWebSocketSession session; if (_sessions.TryGetValue (id, out session)) { var state = session.State; if (state == WebSocketState.Open) session.Context.WebSocket.Close (CloseStatusCode.Abnormal); else if (state == WebSocketState.Closing) continue; else _sessions.Remove (id); } } } _sweeping = false; } } /// /// Tries to get the information in a session with the specified in the /// WebSocket service. /// /// /// true if the session is successfully found; otherwise, false. /// /// /// A that represents the ID of the session to find. /// /// /// When this method returns, a instance that provides the /// access to the session if it's successfully found; otherwise, . This /// parameter is passed uninitialized. /// public bool TryGetSession (string id, out IWebSocketSession session) { var msg = _state.CheckIfStart () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); session = null; return false; } return tryGetSession (id, out session); } #endregion } }