引入 websocket sharp

This commit is contained in:
zhangyazhou
2022-03-14 14:04:39 +08:00
parent 2d0fe5aafb
commit fcb553bfe4
85 changed files with 32965 additions and 11 deletions

View File

@@ -0,0 +1,260 @@
#region License
/*
* HttpRequestEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2021 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.IO;
using System.Security.Principal;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp.Server
{
/// <summary>
/// Represents the event data for the HTTP request events of the
/// <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// <para>
/// An HTTP request event occurs when the <see cref="HttpServer"/>
/// instance receives an HTTP request.
/// </para>
/// <para>
/// You should access the <see cref="Request"/> property if you would
/// like to get the request data sent from a client.
/// </para>
/// <para>
/// And you should access the <see cref="Response"/> property if you
/// would like to get the response data to return to the client.
/// </para>
/// </remarks>
public class HttpRequestEventArgs : EventArgs
{
#region Private Fields
private HttpListenerContext _context;
private string _docRootPath;
#endregion
#region Internal Constructors
internal HttpRequestEventArgs (
HttpListenerContext context, string documentRootPath
)
{
_context = context;
_docRootPath = documentRootPath;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the request data sent from a client.
/// </summary>
/// <value>
/// A <see cref="HttpListenerRequest"/> that provides the methods and
/// properties for the request data.
/// </value>
public HttpListenerRequest Request {
get {
return _context.Request;
}
}
/// <summary>
/// Gets the response data to return to the client.
/// </summary>
/// <value>
/// A <see cref="HttpListenerResponse"/> that provides the methods and
/// properties for the response data.
/// </value>
public HttpListenerResponse Response {
get {
return _context.Response;
}
}
/// <summary>
/// Gets the information for the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="IPrincipal"/> instance or <see langword="null"/>
/// if not authenticated.
/// </para>
/// <para>
/// That instance describes the identity, authentication scheme,
/// and security roles for the client.
/// </para>
/// </value>
public IPrincipal User {
get {
return _context.User;
}
}
#endregion
#region Private Methods
private string createFilePath (string childPath)
{
childPath = childPath.TrimStart ('/', '\\');
return new StringBuilder (_docRootPath, 32)
.AppendFormat ("/{0}", childPath)
.ToString ()
.Replace ('\\', '/');
}
private static bool tryReadFile (string path, out byte[] contents)
{
contents = null;
if (!File.Exists (path))
return false;
try {
contents = File.ReadAllBytes (path);
}
catch {
return false;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Reads the specified file from the document folder of the
/// <see cref="HttpServer"/> class.
/// </summary>
/// <returns>
/// <para>
/// An array of <see cref="byte"/> or <see langword="null"/>
/// if it fails.
/// </para>
/// <para>
/// That array receives the contents of the file.
/// </para>
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that specifies a virtual path to
/// find the file from the document folder.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> contains "..".
/// </para>
/// </exception>
public byte[] ReadFile (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path.IndexOf ("..") > -1)
throw new ArgumentException ("It contains '..'.", "path");
path = createFilePath (path);
byte[] contents;
tryReadFile (path, out contents);
return contents;
}
/// <summary>
/// Tries to read the specified file from the document folder of
/// the <see cref="HttpServer"/> class.
/// </summary>
/// <returns>
/// <c>true</c> if it succeeds to read; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that specifies a virtual path to find
/// the file from the document folder.
/// </param>
/// <param name="contents">
/// <para>
/// When this method returns, an array of <see cref="byte"/> or
/// <see langword="null"/> if it fails.
/// </para>
/// <para>
/// That array receives the contents of the file.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> contains "..".
/// </para>
/// </exception>
public bool TryReadFile (string path, out byte[] contents)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path.IndexOf ("..") > -1)
throw new ArgumentException ("It contains '..'.", "path");
path = createFilePath (path);
return tryReadFile (path, out contents);
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,91 @@
#region License
/*
* IWebSocketSession.cs
*
* The MIT License
*
* Copyright (c) 2013-2018 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 WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Exposes the access to the information in a WebSocket session.
/// </summary>
public interface IWebSocketSession
{
#region Properties
/// <summary>
/// Gets the current state of the WebSocket connection for the session.
/// </summary>
/// <value>
/// <para>
/// One of the <see cref="WebSocketState"/> enum values.
/// </para>
/// <para>
/// It indicates the current state of the connection.
/// </para>
/// </value>
WebSocketState ConnectionState { get; }
/// <summary>
/// Gets the information in the WebSocket handshake request.
/// </summary>
/// <value>
/// A <see cref="WebSocketContext"/> instance that provides the access to
/// the information in the handshake request.
/// </value>
WebSocketContext Context { get; }
/// <summary>
/// Gets the unique ID of the session.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the unique ID of the session.
/// </value>
string ID { get; }
/// <summary>
/// Gets the name of the WebSocket subprotocol for the session.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the subprotocol
/// if present.
/// </value>
string Protocol { get; }
/// <summary>
/// Gets the time that the session has started.
/// </summary>
/// <value>
/// A <see cref="DateTime"/> that represents the time that the session
/// has started.
/// </value>
DateTime StartTime { get; }
#endregion
}
}

View File

@@ -0,0 +1,40 @@
#region License
/*
* ServerState.cs
*
* The MIT License
*
* Copyright (c) 2013-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;
namespace WebSocketSharp.Server
{
internal enum ServerState
{
Ready,
Start,
ShuttingDown,
Stop
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,226 @@
#region License
/*
* WebSocketServiceHost.cs
*
* The MIT License
*
* Copyright (c) 2012-2021 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
#region Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
*/
#endregion
using System;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Exposes the methods and properties used to access the information in
/// a WebSocket service provided by the <see cref="WebSocketServer"/> or
/// <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// This class is an abstract class.
/// </remarks>
public abstract class WebSocketServiceHost
{
#region Private Fields
private Logger _log;
private string _path;
private WebSocketSessionManager _sessions;
#endregion
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServiceHost"/>
/// class with the specified path and logging function.
/// </summary>
/// <param name="path">
/// A <see cref="string"/> that specifies the absolute path to
/// the service.
/// </param>
/// <param name="log">
/// A <see cref="Logger"/> that specifies the logging function for
/// the service.
/// </param>
protected WebSocketServiceHost (string path, Logger log)
{
_path = path;
_log = log;
_sessions = new WebSocketSessionManager (log);
}
#endregion
#region Internal Properties
internal ServerState State {
get {
return _sessions.State;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the logging function for the service.
/// </summary>
/// <value>
/// A <see cref="Logger"/> that provides the logging function.
/// </value>
protected Logger Log {
get {
return _log;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a value indicating whether the service cleans up the
/// inactive sessions periodically.
/// </summary>
/// <remarks>
/// The set operation does nothing if the service has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <c>true</c> if the service cleans up the inactive sessions every
/// 60 seconds; otherwise, <c>false</c>.
/// </value>
public bool KeepClean {
get {
return _sessions.KeepClean;
}
set {
_sessions.KeepClean = value;
}
}
/// <summary>
/// Gets the path to the service.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the absolute path to
/// the service.
/// </value>
public string Path {
get {
return _path;
}
}
/// <summary>
/// Gets the management function for the sessions in the service.
/// </summary>
/// <value>
/// A <see cref="WebSocketSessionManager"/> that manages the sessions in
/// the service.
/// </value>
public WebSocketSessionManager Sessions {
get {
return _sessions;
}
}
/// <summary>
/// Gets the type of the behavior of the service.
/// </summary>
/// <value>
/// A <see cref="Type"/> that represents the type of the behavior of
/// the service.
/// </value>
public abstract Type BehaviorType { get; }
/// <summary>
/// Gets or sets the time to wait for the response to the WebSocket Ping
/// or Close.
/// </summary>
/// <remarks>
/// The set operation does nothing if the service has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// A <see cref="TimeSpan"/> to wait for the response.
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is zero or less.
/// </exception>
public TimeSpan WaitTime {
get {
return _sessions.WaitTime;
}
set {
_sessions.WaitTime = value;
}
}
#endregion
#region Internal Methods
internal void Start ()
{
_sessions.Start ();
}
internal void StartSession (WebSocketContext context)
{
CreateSession ().Start (context, _sessions);
}
internal void Stop (ushort code, string reason)
{
_sessions.Stop (code, reason);
}
#endregion
#region Protected Methods
/// <summary>
/// Creates a new session for the service.
/// </summary>
/// <returns>
/// A <see cref="WebSocketBehavior"/> instance that represents
/// the new session.
/// </returns>
protected abstract WebSocketBehavior CreateSession ();
#endregion
}
}

View File

@@ -0,0 +1,93 @@
#region License
/*
* WebSocketServiceHost`1.cs
*
* The MIT License
*
* Copyright (c) 2015-2021 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;
namespace WebSocketSharp.Server
{
internal class WebSocketServiceHost<TBehavior> : WebSocketServiceHost
where TBehavior : WebSocketBehavior, new ()
{
#region Private Fields
private Func<TBehavior> _creator;
#endregion
#region Internal Constructors
internal WebSocketServiceHost (
string path, Action<TBehavior> initializer, Logger log
)
: base (path, log)
{
_creator = createSessionCreator (initializer);
}
#endregion
#region Public Properties
public override Type BehaviorType {
get {
return typeof (TBehavior);
}
}
#endregion
#region Private Methods
private static Func<TBehavior> createSessionCreator (
Action<TBehavior> initializer
)
{
if (initializer == null)
return () => new TBehavior ();
return () => {
var ret = new TBehavior ();
initializer (ret);
return ret;
};
}
#endregion
#region Protected Methods
protected override WebSocketBehavior CreateSession ()
{
return _creator ();
}
#endregion
}
}

View File

@@ -0,0 +1,609 @@
#region License
/*
* WebSocketServiceManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2021 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
{
/// <summary>
/// Provides the management function for the WebSocket services.
/// </summary>
/// <remarks>
/// This class manages the WebSocket services provided by
/// the <see cref="WebSocketServer"/> or <see cref="HttpServer"/> class.
/// </remarks>
public class WebSocketServiceManager
{
#region Private Fields
private Dictionary<string, WebSocketServiceHost> _hosts;
private volatile bool _keepClean;
private Logger _log;
private volatile ServerState _state;
private object _sync;
private TimeSpan _waitTime;
#endregion
#region Internal Constructors
internal WebSocketServiceManager (Logger log)
{
_log = log;
_hosts = new Dictionary<string, WebSocketServiceHost> ();
_keepClean = true;
_state = ServerState.Ready;
_sync = ((ICollection) _hosts).SyncRoot;
_waitTime = TimeSpan.FromSeconds (1);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of the services.
/// </value>
public int Count {
get {
lock (_sync)
return _hosts.Count;
}
}
/// <summary>
/// Gets the service host instances for the WebSocket services.
/// </summary>
/// <value>
/// <para>
/// An <c>IEnumerable&lt;WebSocketServiceHost&gt;</c> instance.
/// </para>
/// <para>
/// It provides an enumerator which supports the iteration over
/// the collection of the service host instances.
/// </para>
/// </value>
public IEnumerable<WebSocketServiceHost> Hosts {
get {
lock (_sync)
return _hosts.Values.ToList ();
}
}
/// <summary>
/// Gets the service host instance for a WebSocket service with
/// the specified path.
/// </summary>
/// <value>
/// <para>
/// A <see cref="WebSocketServiceHost"/> instance or
/// <see langword="null"/> if not found.
/// </para>
/// <para>
/// The service host instance provides the function to access
/// the information in the service.
/// </para>
/// </value>
/// <param name="path">
/// <para>
/// A <see cref="string"/> that specifies an absolute path to
/// the service to find.
/// </para>
/// <para>
/// / is trimmed from the end of the string if present.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
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] != '/') {
var msg = "It is not an absolute path.";
throw new ArgumentException (msg, "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;
}
}
/// <summary>
/// Gets or sets a value indicating whether the inactive sessions in
/// the WebSocket services are cleaned up periodically.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <para>
/// <c>true</c> if the inactive sessions are cleaned up every 60
/// seconds; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>true</c>.
/// </para>
/// </value>
public bool KeepClean {
get {
return _keepClean;
}
set {
lock (_sync) {
if (!canSet ())
return;
foreach (var host in _hosts.Values)
host.KeepClean = value;
_keepClean = value;
}
}
}
/// <summary>
/// Gets the paths for the WebSocket services.
/// </summary>
/// <value>
/// <para>
/// An <c>IEnumerable&lt;string&gt;</c> instance.
/// </para>
/// <para>
/// It provides an enumerator which supports the iteration over
/// the collection of the paths.
/// </para>
/// </value>
public IEnumerable<string> Paths {
get {
lock (_sync)
return _hosts.Keys.ToList ();
}
}
/// <summary>
/// Gets or sets the time to wait for the response to the WebSocket Ping
/// or Close.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="TimeSpan"/> to wait for the response.
/// </para>
/// <para>
/// The default value is the same as 1 second.
/// </para>
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is zero or less.
/// </exception>
public TimeSpan WaitTime {
get {
return _waitTime;
}
set {
if (value <= TimeSpan.Zero) {
var msg = "It is zero or less.";
throw new ArgumentOutOfRangeException ("value", msg);
}
lock (_sync) {
if (!canSet ())
return;
foreach (var host in _hosts.Values)
host.WaitTime = value;
_waitTime = value;
}
}
}
#endregion
#region Private Methods
private bool canSet ()
{
return _state == ServerState.Ready || _state == ServerState.Stop;
}
#endregion
#region Internal Methods
internal bool InternalTryGetServiceHost (
string path, out WebSocketServiceHost host
)
{
path = path.TrimSlashFromEnd ();
lock (_sync)
return _hosts.TryGetValue (path, out host);
}
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;
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a WebSocket service with the specified behavior, path,
/// and delegate.
/// </summary>
/// <param name="path">
/// <para>
/// A <see cref="string"/> that specifies an absolute path to
/// the service to add.
/// </para>
/// <para>
/// / is trimmed from the end of the string if present.
/// </para>
/// </param>
/// <param name="initializer">
/// <para>
/// An <c>Action&lt;TBehavior&gt;</c> delegate or
/// <see langword="null"/> if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when initializing
/// a new session instance for the service.
/// </para>
/// </param>
/// <typeparam name="TBehavior">
/// <para>
/// The type of the behavior for the service.
/// </para>
/// <para>
/// It must inherit the <see cref="WebSocketBehavior"/> class.
/// </para>
/// <para>
/// And also, it must have a public parameterless constructor.
/// </para>
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is already in use.
/// </para>
/// </exception>
public void AddService<TBehavior> (
string path, Action<TBehavior> 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] != '/') {
var msg = "It is not an absolute path.";
throw new ArgumentException (msg, "path");
}
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
path = path.TrimSlashFromEnd ();
lock (_sync) {
WebSocketServiceHost host;
if (_hosts.TryGetValue (path, out host)) {
var msg = "It is already in use.";
throw new ArgumentException (msg, "path");
}
host = new WebSocketServiceHost<TBehavior> (path, initializer, _log);
if (!_keepClean)
host.KeepClean = false;
if (_waitTime != host.WaitTime)
host.WaitTime = _waitTime;
if (_state == ServerState.Start)
host.Start ();
_hosts.Add (path, host);
}
}
/// <summary>
/// Removes all WebSocket services managed by the manager.
/// </summary>
/// <remarks>
/// A service is stopped with close status 1001 (going away)
/// if it has already started.
/// </remarks>
public void Clear ()
{
List<WebSocketServiceHost> hosts = null;
lock (_sync) {
hosts = _hosts.Values.ToList ();
_hosts.Clear ();
}
foreach (var host in hosts) {
if (host.State == ServerState.Start)
host.Stop (1001, String.Empty);
}
}
/// <summary>
/// Removes a WebSocket service with the specified path.
/// </summary>
/// <remarks>
/// The service is stopped with close status 1001 (going away)
/// if it has already started.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// <para>
/// A <see cref="string"/> that specifies an absolute path to
/// the service to remove.
/// </para>
/// <para>
/// / is trimmed from the end of the string if present.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
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] != '/') {
var msg = "It is not an absolute path.";
throw new ArgumentException (msg, "path");
}
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
path = 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;
}
/// <summary>
/// Tries to get the service host instance for a WebSocket service with
/// the specified path.
/// </summary>
/// <returns>
/// <c>true</c> if the service is successfully found; otherwise,
/// <c>false</c>.
/// </returns>
/// <param name="path">
/// <para>
/// A <see cref="string"/> that specifies an absolute path to
/// the service to find.
/// </para>
/// <para>
/// / is trimmed from the end of the string if present.
/// </para>
/// </param>
/// <param name="host">
/// <para>
/// When this method returns, a <see cref="WebSocketServiceHost"/>
/// instance or <see langword="null"/> if not found.
/// </para>
/// <para>
/// The service host instance provides the function to access
/// the information in the service.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
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] != '/') {
var msg = "It is not an absolute path.";
throw new ArgumentException (msg, "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
}
}

File diff suppressed because it is too large Load Diff