#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 _logger;
private volatile ServerState _state;
private object _sync;
private TimeSpan _waitTime;
#endregion
#region Internal Constructors
internal WebSocketServiceManager ()
: this (new Logger ())
{
}
internal WebSocketServiceManager (Logger logger)
{
_logger = logger;
_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 .
///
///
/// is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
///
///
///
/// A instance or
/// if not found.
///
///
/// That host instance provides the function to access
/// the information in the service.
///
///
///
/// A that represents an absolute path to
/// the service to find.
///
///
/// 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 a value indicating whether the inactive sessions in
/// the WebSocket services are cleaned up periodically.
///
///
/// true if the inactive sessions in the services are
/// cleaned up every 60 seconds; otherwise, false.
///
public bool KeepClean {
get {
return _clean;
}
internal set {
lock (_sync) {
_clean = value;
foreach (var host in _hosts.Values)
host.KeepClean = 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 the wait time for the response to the WebSocket Ping or Close.
///
///
/// A that represents the wait time for the response.
///
public TimeSpan WaitTime {
get {
return _waitTime;
}
internal set {
lock (_sync) {
_waitTime = value;
foreach (var host in _hosts.Values)
host.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)
break;
host.Sessions.Broadcast (opcode, data, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.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)
break;
host.Sessions.Broadcast (opcode, stream, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Error (ex.Message);
_logger.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)
break;
ret.Add (host.Path, host.Sessions.Broadping (frameAsBytes, timeout));
}
return ret;
}
#endregion
#region Internal Methods
internal void Add (string path, Func creator)
where TBehavior : WebSocketBehavior
{
path = HttpUtility.UrlDecode (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, _logger
);
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 = HttpUtility.UrlDecode (path).TrimSlashFromEnd ();
lock (_sync)
return _hosts.TryGetValue (path, out host);
}
internal bool Remove (string path)
{
path = HttpUtility.UrlDecode (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;
}
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;
}
}
internal void Stop (CloseEventArgs e, bool send, bool receive)
{
lock (_sync) {
_state = ServerState.ShuttingDown;
var bytes = send ? WebSocketFrame.CreateCloseFrame (e.PayloadData, false).ToArray () : null;
foreach (var host in _hosts.Values)
host.Sessions.Stop (e, bytes, receive);
_hosts.Clear ();
_state = ServerState.Stop;
}
}
#endregion
#region Public Methods
///
/// Adds a WebSocket service with the specified behavior,
/// , and .
///
///
/// is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
///
///
/// A that represents an absolute path to
/// the service to add.
///
///
/// An Action<TBehavior> delegate that invokes
/// the method used to initialize a new session instance for
/// the service or if not needed.
///
///
/// The type of the behavior for the service. It must inherit
/// the class and 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 = HttpUtility.UrlDecode (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, _logger
);
if (!_clean)
host.KeepClean = false;
if (_waitTime != host.WaitTime)
host.WaitTime = _waitTime;
if (_state == ServerState.Start)
host.Start ();
_hosts.Add (path, host);
}
}
///
/// Sends the specified 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 the specified 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 the specified 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.
///
///
/// That 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 the specified 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.
///
///
/// That 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 specified of data from
/// the specified asynchronously to
/// every client in the WebSocket services.
///
///
/// This method does not wait for the send to be complete.
///
///
/// A from which to read the binary data to send.
///
///
/// An that specifies the number of bytes to
/// read and send.
///
///
///
/// An delegate or
/// if not needed.
///
///
/// That 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)
throw new ArgumentException ("It cannot be read.", "stream");
if (length < 1)
throw new ArgumentException ("It is less than 1.", "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) {
_logger.Warn (
String.Format (
"Only {0} byte(s) of data could be read from the specified 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 within a time
/// from its client.
///
///
///
/// 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 the specified to
/// every client in the WebSocket services.
///
///
///
/// A Dictionary<string, Dictionary<string, bool>>.
///
///
/// It contains 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 within a time
/// from a client.
///
///
///
/// 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.
///
///
/// is .
///
///
/// could not be UTF-8-encoded.
///
///
/// The size of is greater than 125 bytes.
///
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 == null)
throw new ArgumentNullException ("message");
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 a WebSocket service with the specified .
///
///
///
/// is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
///
///
/// 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 .
///
///
///
/// 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 = HttpUtility.UrlDecode (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 .
///
///
/// is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
///
///
/// true if the service is successfully found;
/// otherwise, false.
///
///
/// A that represents an absolute path to
/// the service to find.
///
///
///
/// When this method returns, a
/// instance or if not found.
///
///
/// That 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
}
}