#region License
/*
* WebSocketSessionManager.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.Linq;
using System.Text;
using System.Threading;
using System.Timers;
namespace WebSocketSharp.Server
{
///
/// Provides the management function for the sessions in a WebSocket service.
///
///
/// This class manages the sessions in a WebSocket service provided by
/// the or .
///
public class WebSocketSessionManager
{
#region Private Fields
private volatile bool _clean;
private object _forSweep;
private Logger _log;
private Dictionary _sessions;
private volatile ServerState _state;
private volatile bool _sweeping;
private System.Timers.Timer _sweepTimer;
private object _sync;
private TimeSpan _waitTime;
#endregion
#region Internal Constructors
internal WebSocketSessionManager (Logger log)
{
_log = log;
_clean = true;
_forSweep = new object ();
_sessions = new Dictionary ();
_state = ServerState.Ready;
_sync = ((ICollection) _sessions).SyncRoot;
_waitTime = TimeSpan.FromSeconds (1);
setSweepTimer (60000);
}
#endregion
#region Internal Properties
internal ServerState State {
get {
return _state;
}
}
#endregion
#region Public Properties
///
/// Gets the IDs for the active sessions in the WebSocket service.
///
///
///
/// An IEnumerable<string> instance.
///
///
/// It provides an enumerator which supports the iteration over
/// the collection of the IDs for the active sessions.
///
///
public IEnumerable ActiveIDs {
get {
foreach (var res in broadping (WebSocketFrame.EmptyPingBytes)) {
if (res.Value)
yield return res.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 IDs for the sessions in the WebSocket service.
///
///
///
/// An IEnumerable<string> instance.
///
///
/// It provides an enumerator which supports the iteration over
/// the collection of the IDs for the sessions.
///
///
public IEnumerable IDs {
get {
if (_state != ServerState.Start)
return Enumerable.Empty ();
lock (_sync) {
if (_state != ServerState.Start)
return Enumerable.Empty ();
return _sessions.Keys.ToList ();
}
}
}
///
/// Gets the IDs for the inactive sessions in the WebSocket service.
///
///
///
/// An IEnumerable<string> instance.
///
///
/// It provides an enumerator which supports the iteration over
/// the collection of the IDs for the inactive sessions.
///
///
public IEnumerable InactiveIDs {
get {
foreach (var res in broadping (WebSocketFrame.EmptyPingBytes)) {
if (!res.Value)
yield return res.Key;
}
}
}
///
/// Gets the session instance with .
///
///
///
/// A instance or
/// if not found.
///
///
/// The session instance provides the function to access the information
/// in the session.
///
///
///
/// A that represents the ID of the session to find.
///
///
/// is .
///
///
/// is an empty string.
///
public IWebSocketSession this[string id] {
get {
if (id == null)
throw new ArgumentNullException ("id");
if (id.Length == 0)
throw new ArgumentException ("An empty string.", "id");
IWebSocketSession session;
tryGetSession (id, out session);
return session;
}
}
///
/// Gets or sets a value indicating whether the inactive sessions in
/// the WebSocket service are cleaned up periodically.
///
///
/// The set operation does nothing if the service has already started or
/// it is shutting down.
///
///
/// true if the inactive sessions are cleaned up every 60 seconds;
/// otherwise, false.
///
public bool KeepClean {
get {
return _clean;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_clean = value;
}
}
}
///
/// Gets the session instances in the WebSocket service.
///
///
///
/// An IEnumerable<IWebSocketSession> instance.
///
///
/// It provides an enumerator which supports the iteration over
/// the collection of the session instances.
///
///
public IEnumerable Sessions {
get {
if (_state != ServerState.Start)
return Enumerable.Empty ();
lock (_sync) {
if (_state != ServerState.Start)
return Enumerable.Empty ();
return _sessions.Values.ToList ();
}
}
}
///
/// Gets or sets the time to wait for the response to the WebSocket Ping or
/// Close.
///
///
/// The set operation does nothing if the service has already started or
/// it is shutting down.
///
///
/// A to wait for the response.
///
///
/// The value specified for a set operation is zero or less.
///
public TimeSpan WaitTime {
get {
return _waitTime;
}
set {
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("value", "Zero or less.");
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_waitTime = value;
}
}
}
#endregion
#region Private Methods
private void broadcast (Opcode opcode, byte[] data, Action completed)
{
var cache = new Dictionary ();
try {
foreach (var session in Sessions) {
if (_state != ServerState.Start) {
_log.Error ("The service is shutting down.");
break;
}
session.Context.WebSocket.Send (opcode, data, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_log.Error (ex.Message);
_log.Debug (ex.ToString ());
}
finally {
cache.Clear ();
}
}
private void broadcast (Opcode opcode, Stream stream, Action completed)
{
var cache = new Dictionary ();
try {
foreach (var session in Sessions) {
if (_state != ServerState.Start) {
_log.Error ("The service is shutting down.");
break;
}
session.Context.WebSocket.Send (opcode, stream, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_log.Error (ex.Message);
_log.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)
{
var ret = new Dictionary ();
foreach (var session in Sessions) {
if (_state != ServerState.Start) {
_log.Error ("The service is shutting down.");
break;
}
var res = session.Context.WebSocket.Ping (frameAsBytes, _waitTime);
ret.Add (session.ID, res);
}
return ret;
}
private bool canSet (out string message)
{
message = null;
if (_state == ServerState.Start) {
message = "The service has already started.";
return false;
}
if (_state == ServerState.ShuttingDown) {
message = "The service is shutting down.";
return false;
}
return true;
}
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 void stop (PayloadData payloadData, bool send)
{
var bytes = send
? WebSocketFrame.CreateCloseFrame (payloadData, false).ToArray ()
: null;
lock (_sync) {
_state = ServerState.ShuttingDown;
_sweepTimer.Enabled = false;
foreach (var session in _sessions.Values.ToList ())
session.Context.WebSocket.Close (payloadData, bytes);
_state = ServerState.Stop;
}
}
private bool tryGetSession (string id, out IWebSocketSession session)
{
session = null;
if (_state != ServerState.Start)
return false;
lock (_sync) {
if (_state != ServerState.Start)
return false;
return _sessions.TryGetValue (id, out session);
}
}
#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) {
_log.Error ("The service is shutting down.");
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) {
_log.Error ("The service is shutting down.");
break;
}
session.Context.WebSocket.Send (opcode, stream, cache);
}
}
internal Dictionary Broadping (
byte[] frameAsBytes, TimeSpan timeout
)
{
var ret = new Dictionary ();
foreach (var session in Sessions) {
if (_state != ServerState.Start) {
_log.Error ("The service is shutting down.");
break;
}
var res = session.Context.WebSocket.Ping (frameAsBytes, timeout);
ret.Add (session.ID, res);
}
return ret;
}
internal bool Remove (string id)
{
lock (_sync)
return _sessions.Remove (id);
}
internal void Start ()
{
lock (_sync) {
_sweepTimer.Enabled = _clean;
_state = ServerState.Start;
}
}
internal void Stop (ushort code, string reason)
{
if (code == 1005) { // == no status
stop (PayloadData.Empty, true);
return;
}
stop (new PayloadData (code, reason), !code.IsReserved ());
}
#endregion
#region Public Methods
///
/// Sends to every client in the WebSocket service.
///
///
/// An array of that represents the binary data to send.
///
///
/// The current state of the manager is not Start.
///
///
/// is .
///
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 to every client in the WebSocket service.
///
///
/// A that represents the text data to send.
///
///
/// The current state of the manager is not Start.
///
///
/// is .
///
///
/// could not be UTF-8-encoded.
///
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 data from to every client in
/// the WebSocket service.
///
///
/// The data is sent as the binary data.
///
///
/// A instance from which to read the data to send.
///
///
/// An that specifies the number of bytes to send.
///
///
/// 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 .
///
///
public void Broadcast (Stream stream, int length)
{
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) {
var msg = "It cannot be read.";
throw new ArgumentException (msg, "stream");
}
if (length < 1) {
var msg = "Less than 1.";
throw new ArgumentException (msg, "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) {
_log.Warn (
String.Format (
"Only {0} byte(s) of data could be read from the stream.",
len
)
);
}
if (len <= WebSocket.FragmentLength)
broadcast (Opcode.Binary, bytes, null);
else
broadcast (Opcode.Binary, new MemoryStream (bytes), null);
}
///
/// Sends asynchronously to every client in
/// the WebSocket service.
///
///
/// 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.
///
///
/// The delegate invokes the method called when the send is complete.
///
///
///
/// The current state of the manager is not Start.
///
///
/// is .
///
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 asynchronously to every client in
/// the WebSocket service.
///
///
/// 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.
///
///
/// The 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.
///
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 data from asynchronously to
/// every client in the WebSocket service.
///
///
///
/// The data is sent as the binary data.
///
///
/// This method does not wait for the send to be complete.
///
///
///
/// A instance from which to read the data to send.
///
///
/// An that specifies the number of bytes to send.
///
///
///
/// An delegate or
/// if not needed.
///
///
/// The 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 .
///
///
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) {
var msg = "It cannot be read.";
throw new ArgumentException (msg, "stream");
}
if (length < 1) {
var msg = "Less than 1.";
throw new ArgumentException (msg, "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) {
_log.Warn (
String.Format (
"Only {0} byte(s) of data could be read from the 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 service.
///
///
///
/// A Dictionary<string, bool>.
///
///
/// It represents a collection of pairs of a session ID and
/// a value indicating whether a pong has been received from
/// the client within a time.
///
///
///
/// 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 to every client in
/// the WebSocket service.
///
///
///
/// A Dictionary<string, bool>.
///
///
/// It represents a collection of pairs of a session ID and
/// a value indicating whether a pong has been received from
/// the client within a time.
///
///
///
///
/// 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.
///
///
/// could not be UTF-8-encoded.
///
///
/// The size of is greater than 125 bytes.
///
[Obsolete ("This method will be removed.")]
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.IsNullOrEmpty ())
return Broadping (WebSocketFrame.EmptyPingBytes, _waitTime);
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);
}
///
/// Closes the specified session.
///
///
/// A that represents the ID of the session to close.
///
///
/// is .
///
///
/// is an empty string.
///
///
/// The session could not be found.
///
public void CloseSession (string id)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.Close ();
}
///
/// Closes the specified session with and
/// .
///
///
/// A that represents the ID of the session to close.
///
///
///
/// A that represents the status code indicating
/// the reason for the close.
///
///
/// The status codes are defined in
///
/// Section 7.4 of RFC 6455.
///
///
///
///
/// A that represents the reason for the close.
///
///
/// The size must be 123 bytes or less in UTF-8.
///
///
///
/// is .
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// is 1010 (mandatory extension).
///
///
/// -or-
///
///
/// is 1005 (no status) and there is
/// .
///
///
/// -or-
///
///
/// could not be UTF-8-encoded.
///
///
///
/// The session could not be found.
///
///
///
/// is less than 1000 or greater than 4999.
///
///
/// -or-
///
///
/// The size of is greater than 123 bytes.
///
///
public void CloseSession (string id, ushort code, string reason)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.Close (code, reason);
}
///
/// Closes the specified session with and
/// .
///
///
/// A that represents the ID of the session to close.
///
///
///
/// One of the enum values.
///
///
/// It represents the status code indicating the reason for the close.
///
///
///
///
/// A that represents the reason for the close.
///
///
/// The size must be 123 bytes or less in UTF-8.
///
///
///
/// is .
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// is
/// .
///
///
/// -or-
///
///
/// is
/// and there is
/// .
///
///
/// -or-
///
///
/// could not be UTF-8-encoded.
///
///
///
/// The session could not be found.
///
///
/// The size of is greater than 123 bytes.
///
public void CloseSession (string id, CloseStatusCode code, string reason)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.Close (code, reason);
}
///
/// Sends a ping to the client using the specified session.
///
///
/// true if the send has done with no error and a pong has been
/// received from the client within a time; otherwise, false.
///
///
/// A that represents the ID of the session.
///
///
/// is .
///
///
/// is an empty string.
///
///
/// The session could not be found.
///
public bool PingTo (string id)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
return session.Context.WebSocket.Ping ();
}
///
/// Sends a ping with to the client using
/// the specified session.
///
///
/// true if the send has done with no error and a pong has been
/// received from the client within a time; otherwise, false.
///
///
///
/// A that represents the message to send.
///
///
/// The size must be 125 bytes or less in UTF-8.
///
///
///
/// A that represents the ID of the session.
///
///
/// is .
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// could not be UTF-8-encoded.
///
///
///
/// The session could not be found.
///
///
/// The size of is greater than 125 bytes.
///
public bool PingTo (string message, string id)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
return session.Context.WebSocket.Ping (message);
}
///
/// Sends to the client using the specified session.
///
///
/// An array of that represents the binary data to send.
///
///
/// A that represents the ID of the session.
///
///
///
/// is .
///
///
/// -or-
///
///
/// is .
///
///
///
/// is an empty string.
///
///
///
/// The session could not be found.
///
///
/// -or-
///
///
/// The current state of the WebSocket connection is not Open.
///
///
public void SendTo (byte[] data, string id)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.Send (data);
}
///
/// Sends to the client using the specified session.
///
///
/// A that represents the text data to send.
///
///
/// A that represents the ID of the session.
///
///
///
/// is .
///
///
/// -or-
///
///
/// is .
///
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// could not be UTF-8-encoded.
///
///
///
///
/// The session could not be found.
///
///
/// -or-
///
///
/// The current state of the WebSocket connection is not Open.
///
///
public void SendTo (string data, string id)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.Send (data);
}
///
/// Sends the data from to the client using
/// the specified session.
///
///
/// The data is sent as the binary data.
///
///
/// A instance from which to read the data to send.
///
///
/// An that specifies the number of bytes to send.
///
///
/// A that represents the ID of the session.
///
///
///
/// is .
///
///
/// -or-
///
///
/// is .
///
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// cannot be read.
///
///
/// -or-
///
///
/// is less than 1.
///
///
/// -or-
///
///
/// No data could be read from .
///
///
///
///
/// The session could not be found.
///
///
/// -or-
///
///
/// The current state of the WebSocket connection is not Open.
///
///
public void SendTo (Stream stream, int length, string id)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.Send (stream, length);
}
///
/// Sends asynchronously to the client using
/// the specified session.
///
///
/// This method does not wait for the send to be complete.
///
///
/// An array of that represents the binary data to send.
///
///
/// A that represents the ID of the session.
///
///
///
/// An Action<bool> delegate or
/// if not needed.
///
///
/// The delegate invokes the method called when the send is complete.
///
///
/// true is passed to the method if the send has done with
/// no error; otherwise, false.
///
///
///
///
/// is .
///
///
/// -or-
///
///
/// is .
///
///
///
/// is an empty string.
///
///
///
/// The session could not be found.
///
///
/// -or-
///
///
/// The current state of the WebSocket connection is not Open.
///
///
public void SendToAsync (byte[] data, string id, Action completed)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.SendAsync (data, completed);
}
///
/// Sends asynchronously to the client using
/// the specified session.
///
///
/// This method does not wait for the send to be complete.
///
///
/// A that represents the text data to send.
///
///
/// A that represents the ID of the session.
///
///
///
/// An Action<bool> delegate or
/// if not needed.
///
///
/// The delegate invokes the method called when the send is complete.
///
///
/// true is passed to the method if the send has done with
/// no error; otherwise, false.
///
///
///
///
/// is .
///
///
/// -or-
///
///
/// is .
///
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// could not be UTF-8-encoded.
///
///
///
///
/// The session could not be found.
///
///
/// -or-
///
///
/// The current state of the WebSocket connection is not Open.
///
///
public void SendToAsync (string data, string id, Action completed)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.SendAsync (data, completed);
}
///
/// Sends the data from asynchronously to
/// the client using the specified session.
///
///
///
/// The data is sent as the binary data.
///
///
/// This method does not wait for the send to be complete.
///
///
///
/// A instance from which to read the data to send.
///
///
/// An that specifies the number of bytes to send.
///
///
/// A that represents the ID of the session.
///
///
///
/// An Action<bool> delegate or
/// if not needed.
///
///
/// The delegate invokes the method called when the send is complete.
///
///
/// true is passed to the method if the send has done with
/// no error; otherwise, false.
///
///
///
///
/// is .
///
///
/// -or-
///
///
/// is .
///
///
///
///
/// is an empty string.
///
///
/// -or-
///
///
/// cannot be read.
///
///
/// -or-
///
///
/// is less than 1.
///
///
/// -or-
///
///
/// No data could be read from .
///
///
///
///
/// The session could not be found.
///
///
/// -or-
///
///
/// The current state of the WebSocket connection is not Open.
///
///
public void SendToAsync (
Stream stream, int length, string id, Action completed
)
{
IWebSocketSession session;
if (!TryGetSession (id, out session)) {
var msg = "The session could not be found.";
throw new InvalidOperationException (msg);
}
session.Context.WebSocket.SendAsync (stream, length, completed);
}
///
/// Cleans up the inactive sessions in the WebSocket service.
///
public void Sweep ()
{
if (_sweeping) {
_log.Info ("The sweeping is already in progress.");
return;
}
lock (_forSweep) {
if (_sweeping) {
_log.Info ("The sweeping is already in progress.");
return;
}
_sweeping = true;
}
foreach (var id in InactiveIDs) {
if (_state != ServerState.Start)
break;
lock (_sync) {
if (_state != ServerState.Start)
break;
IWebSocketSession session;
if (_sessions.TryGetValue (id, out session)) {
var state = session.ConnectionState;
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 instance with .
///
///
/// 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 or if not found.
///
///
/// The session instance provides the function to access
/// the information in the session.
///
///
///
/// is .
///
///
/// is an empty string.
///
public bool TryGetSession (string id, out IWebSocketSession session)
{
if (id == null)
throw new ArgumentNullException ("id");
if (id.Length == 0)
throw new ArgumentException ("An empty string.", "id");
return tryGetSession (id, out session);
}
#endregion
}
}