#region License /* * WebSocketSessionManager.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 System.Timers; namespace WebSocketSharp.Server { /// /// Manages the sessions to the Websocket service. /// public class WebSocketSessionManager { #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 Timer _sweepTimer; private object _sync; #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; _sweeping = false; _sync = new object (); setSweepTimer (60 * 1000); } #endregion #region Internal Properties internal ServerState State { get { return _state; } } internal IEnumerable ServiceInstances { get { if (_state != ServerState.START) return new List (); lock (_sync) { return _sessions.Values.ToList (); } } } #endregion #region Public Properties /// /// Gets the collection of every ID of the active sessions to the Websocket service. /// /// /// An IEnumerable<string> that contains the collection of every ID of the active sessions. /// public IEnumerable ActiveIDs { get { return from result in BroadpingInternally (new byte [] {}) where result.Value select result.Key; } } /// /// Gets the number of the sessions to the Websocket service. /// /// /// An that contains the number of the sessions. /// public int Count { get { lock (_sync) { return _sessions.Count; } } } /// /// Gets the collection of every ID of the sessions to the Websocket service. /// /// /// An IEnumerable<string> that contains the collection of every ID of the sessions. /// public IEnumerable IDs { get { lock (_sync) { return _sessions.Keys.ToList (); } } } /// /// Gets the collection of every ID of the inactive sessions to the Websocket service. /// /// /// An IEnumerable<string> that contains the collection of every ID of the inactive sessions. /// public IEnumerable InactiveIDs { get { return from result in BroadpingInternally (new byte [] {}) where !result.Value select result.Key; } } /// /// Gets the session information with the specified . /// /// /// A instance with if it is successfully found; /// otherwise, . /// /// /// A that contains the ID of the session information to get. /// public IWebSocketSession this [string id] { get { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return null; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); 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 the session informations to the Websocket service. /// /// /// An IEnumerable<IWebSocketSession> that contains the collection of the session informations. /// public IEnumerable Sessions { get { return from IWebSocketSession session in ServiceInstances select session; } } #endregion #region Private Methods private static string createID () { return Guid.NewGuid ().ToString ("N"); } private void setSweepTimer (double interval) { _sweepTimer = new Timer (interval); _sweepTimer.Elapsed += (sender, e) => { Sweep (); }; } #endregion #region Internal Methods internal string Add (WebSocketService session) { lock (_sync) { if (_state != ServerState.START) return null; var id = createID (); _sessions.Add (id, session); return id; } } internal void BroadcastInternally (byte [] data) { var services = ServiceInstances.GetEnumerator (); Action completed = null; completed = () => { if (_state == ServerState.START && services.MoveNext ()) services.Current.SendAsync (data, completed); }; if (_state == ServerState.START && services.MoveNext ()) services.Current.SendAsync (data, completed); } internal void BroadcastInternally (string data) { var services = ServiceInstances.GetEnumerator (); Action completed = null; completed = () => { if (_state == ServerState.START && services.MoveNext ()) services.Current.SendAsync (data, completed); }; if (_state == ServerState.START && services.MoveNext ()) services.Current.SendAsync (data, completed); } internal Dictionary BroadpingInternally (byte [] data) { var result = new Dictionary (); foreach (var session in ServiceInstances) { if (_state != ServerState.START) break; result.Add (session.ID, session.Context.WebSocket.Ping (data)); } 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 () { lock (_sync) { _state = ServerState.SHUTDOWN; _sweepTimer.Enabled = false; foreach (var session in _sessions.Values.ToList ()) session.Context.WebSocket.Close (); _state = ServerState.STOP; } } internal void Stop (byte [] data) { lock (_sync) { _state = ServerState.SHUTDOWN; _sweepTimer.Enabled = false; foreach (var session in _sessions.Values.ToList ()) session.Context.WebSocket.Close (data); _state = ServerState.STOP; } } internal bool TryGetServiceInstance (string id, out WebSocketService service) { lock (_sync) { return _sessions.TryGetValue (id, out service); } } #endregion #region Public Methods /// /// Broadcasts the specified array of to all clients of the WebSocket service. /// /// /// An array of to broadcast. /// public void Broadcast (byte [] data) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } BroadcastInternally (data); } /// /// Broadcasts the specified to all clients of the WebSocket service. /// /// /// A to broadcast. /// public void Broadcast (string data) { var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } BroadcastInternally (data); } /// /// Sends Pings to all clients of the WebSocket service. /// /// /// 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. /// public Dictionary Broadping () { var msg = _state.CheckIfStarted (); if (msg != null) { _logger.Error (msg); return null; } return BroadpingInternally (new byte [] {}); } /// /// Sends Pings with the specified to all clients of the WebSocket service. /// /// /// 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. /// /// /// 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 BroadpingInternally (data); } /// /// Closes the session with the specified . /// /// /// A that contains a session ID to find. /// public void CloseSession (string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return; } session.Context.WebSocket.Close (); } /// /// 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. /// public void CloseSession (ushort code, string reason, string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return; } session.Context.WebSocket.Close (code, reason); } /// /// 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. /// public void CloseSession (CloseStatusCode code, string reason, string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return; } session.Context.WebSocket.Close (code, reason); } /// /// Sends a Ping to the client associated with the specified . /// /// /// true if the WebSocket service receives a Pong from the client in a time; /// otherwise, false. /// /// /// A that contains a session ID that represents the destination for the Ping. /// public bool PingTo (string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return false; } return session.Context.WebSocket.Ping (); } /// /// Sends a Ping with the specified to the client associated with /// the specified . /// /// /// true if the WebSocket service 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. /// public bool PingTo (string message, string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return false; } return session.Context.WebSocket.Ping (message); } /// /// Sends a binary to the client associated with the specified /// . /// /// /// 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. /// public bool SendTo (byte [] data, string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService service; if (!TryGetServiceInstance (id, out service)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return false; } service.Send (data); return true; } /// /// Sends a text to the client associated with the specified /// . /// /// /// 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. /// public bool SendTo (string data, string id) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService service; if (!TryGetServiceInstance (id, out service)) { _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); return false; } service.Send (data); return true; } /// /// Cleans up the inactive sessions. /// 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) { WebSocketService 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 session information with the specified . /// /// /// true if the session information is successfully found; /// otherwise, false. /// /// /// A that contains the ID of the session information to get. /// /// /// When this method returns, a instance that contains the session /// information if it is successfully found; otherwise, . /// This parameter is passed uninitialized. /// public bool TryGetSession (string id, out IWebSocketSession session) { var msg = _state.CheckIfStarted () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); session = null; return false; } WebSocketService service; var result = TryGetServiceInstance (id, out service); if (!result) _logger.Error ("The WebSocket session with the specified ID not found.\nID: " + id); session = service; return result; } #endregion } }