Modified WebSocketServerBase.cs

This commit is contained in:
sta 2013-07-24 17:47:29 +09:00
parent cd7dfea62d
commit c365d1b521

View File

@ -34,16 +34,16 @@ using System.Security.Cryptography.X509Certificates;
using System.Threading; using System.Threading;
using WebSocketSharp.Net.WebSockets; using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server { namespace WebSocketSharp.Server
{
/// <summary> /// <summary>
/// Provides the basic functions of the server that receives the WebSocket connection requests. /// Provides the basic functions of the server that receives the WebSocket connection requests.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The WebSocketServerBase class is an abstract class. /// The WebSocketServerBase class is an abstract class.
/// </remarks> /// </remarks>
public abstract class WebSocketServerBase { public abstract class WebSocketServerBase
{
#region Private Fields #region Private Fields
private IPAddress _address; private IPAddress _address;
@ -67,8 +67,8 @@ namespace WebSocketSharp.Server {
/// <remarks> /// <remarks>
/// This constructor initializes a new instance of this class as non self hosted server. /// This constructor initializes a new instance of this class as non self hosted server.
/// </remarks> /// </remarks>
protected WebSocketServerBase() protected WebSocketServerBase ()
: this(new Logger()) : this (new Logger ())
{ {
} }
@ -82,7 +82,7 @@ namespace WebSocketSharp.Server {
/// <param name="logger"> /// <param name="logger">
/// A <see cref="Logger"/> that provides the logging functions. /// A <see cref="Logger"/> that provides the logging functions.
/// </param> /// </param>
protected WebSocketServerBase(Logger logger) protected WebSocketServerBase (Logger logger)
{ {
_logger = logger; _logger = logger;
_selfHost = false; _selfHost = false;
@ -101,17 +101,17 @@ namespace WebSocketSharp.Server {
/// <exception cref="ArgumentException"> /// <exception cref="ArgumentException">
/// <paramref name="url"/> is invalid. /// <paramref name="url"/> is invalid.
/// </exception> /// </exception>
protected WebSocketServerBase(string url) protected WebSocketServerBase (string url)
{ {
if (url.IsNull()) if (url == null)
throw new ArgumentNullException("url"); throw new ArgumentNullException ("url");
Uri uri; Uri uri;
string msg; string msg;
if (!tryCreateUri(url, out uri, out msg)) if (!tryCreateUri (url, out uri, out msg))
throw new ArgumentException(msg, "url"); throw new ArgumentException (msg, "url");
init(uri); init (uri);
} }
/// <summary> /// <summary>
@ -146,32 +146,32 @@ namespace WebSocketSharp.Server {
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid. /// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid.
/// </para> /// </para>
/// </exception> /// </exception>
protected WebSocketServerBase(IPAddress address, int port, string absPath, bool secure) protected WebSocketServerBase (IPAddress address, int port, string absPath, bool secure)
{ {
if (address.IsNull()) if (address == null)
throw new ArgumentNullException("address"); throw new ArgumentNullException ("address");
if (absPath.IsNull()) if (absPath == null)
throw new ArgumentNullException("absPath"); throw new ArgumentNullException ("absPath");
string msg; string msg;
if (!absPath.IsValidAbsolutePath(out msg)) if (!absPath.IsValidAbsolutePath (out msg))
throw new ArgumentException(msg, "absPath"); throw new ArgumentException (msg, "absPath");
if ((port == 80 && secure) || if ((port == 80 && secure) ||
(port == 443 && !secure)) (port == 443 && !secure))
{ {
msg = String.Format( msg = String.Format (
"Invalid pair of 'port' and 'secure': {0}, {1}", port, secure); "Invalid pair of 'port' and 'secure': {0}, {1}", port, secure);
throw new ArgumentException(msg); throw new ArgumentException (msg);
} }
_address = address; _address = address;
_port = port > 0 ? port : secure ? 443 : 80; _port = port > 0 ? port : secure ? 443 : 80;
_uri = absPath.ToUri(); _uri = absPath.ToUri ();
_secure = secure; _secure = secure;
init(); init ();
} }
#endregion #endregion
@ -270,7 +270,7 @@ namespace WebSocketSharp.Server {
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The default logging level is the <see cref="LogLevel.ERROR"/>. /// The default logging level is the <see cref="LogLevel.ERROR"/>.
/// If you wanted to change the current logging level, you would set the <c>Log.Level</c> property /// If you want to change the current logging level, you set the <c>Log.Level</c> property
/// to one of the <see cref="LogLevel"/> values which you want. /// to one of the <see cref="LogLevel"/> values which you want.
/// </remarks> /// </remarks>
/// <value> /// <value>
@ -314,87 +314,83 @@ namespace WebSocketSharp.Server {
#region Private Methods #region Private Methods
private void error(string message) private void error (string message)
{ {
OnError.Emit(this, new ErrorEventArgs(message)); OnError.Emit (this, new ErrorEventArgs (message));
} }
private void init() private void init ()
{ {
_listening = false; _listening = false;
_logger = new Logger(); _logger = new Logger ();
_selfHost = true; _selfHost = true;
_listener = new TcpListener(_address, _port); _listener = new TcpListener (_address, _port);
} }
private void init(Uri uri) private void init (Uri uri)
{ {
var scheme = uri.Scheme; var scheme = uri.Scheme;
var host = uri.DnsSafeHost; var host = uri.DnsSafeHost;
var port = uri.Port; var port = uri.Port;
var addrs = Dns.GetHostAddresses(host); var addrs = Dns.GetHostAddresses (host);
_uri = uri; _uri = uri;
_address = addrs[0]; _address = addrs [0];
_secure = scheme == "wss" ? true : false; _secure = scheme == "wss" ? true : false;
_port = port > 0 ? port : _secure ? 443 : 80; _port = port > 0 ? port : _secure ? 443 : 80;
init(); init ();
} }
private void processRequestAsync(TcpClient client) private void processRequestAsync (TcpClient client)
{ {
WaitCallback callback = state => WaitCallback callback = state =>
{ {
try try {
{ AcceptWebSocket (client.GetWebSocketContext (_secure, _cert));
AcceptWebSocket(client.GetWebSocketContext(_secure, _cert));
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.Fatal(ex.Message); _logger.Fatal (ex.Message);
error("An exception has occured."); error ("An exception has occured.");
} }
}; };
ThreadPool.QueueUserWorkItem(callback); ThreadPool.QueueUserWorkItem (callback);
} }
private void receiveRequest() private void receiveRequest ()
{ {
while (true) while (true)
{ {
try try {
{ processRequestAsync (_listener.AcceptTcpClient ());
processRequestAsync(_listener.AcceptTcpClient());
} }
catch (SocketException) catch (SocketException) {
{ _logger.Info ("TcpListener has been stopped.");
_logger.Info("TcpListener has been stopped.");
break; break;
} }
catch (Exception ex) catch (Exception ex) {
{ _logger.Fatal (ex.Message);
_logger.Fatal(ex.Message); error ("An exception has occured.");
error("An exception has occured.");
break; break;
} }
} }
} }
private void startReceiveRequestThread() private void startReceiveRequestThread ()
{ {
_receiveRequestThread = new Thread(new ThreadStart(receiveRequest)); _receiveRequestThread = new Thread (new ThreadStart (receiveRequest));
_receiveRequestThread.IsBackground = true; _receiveRequestThread.IsBackground = true;
_receiveRequestThread.Start(); _receiveRequestThread.Start ();
} }
private static bool tryCreateUri(string uriString, out Uri result, out string message) private static bool tryCreateUri (string uriString, out Uri result, out string message)
{ {
if (!uriString.TryCreateWebSocketUri(out result, out message)) if (!uriString.TryCreateWebSocketUri (out result, out message))
return false; return false;
if (!result.Query.IsNullOrEmpty()) if (!result.Query.IsNullOrEmpty ())
{ {
result = null; result = null;
message = "Must not contain the query component: " + uriString; message = "Must not contain the query component: " + uriString;
@ -415,7 +411,7 @@ namespace WebSocketSharp.Server {
/// <param name="context"> /// <param name="context">
/// A <see cref="TcpListenerWebSocketContext"/> that contains the WebSocket connection request objects. /// A <see cref="TcpListenerWebSocketContext"/> that contains the WebSocket connection request objects.
/// </param> /// </param>
protected abstract void AcceptWebSocket(TcpListenerWebSocketContext context); protected abstract void AcceptWebSocket (TcpListenerWebSocketContext context);
/// <summary> /// <summary>
/// Occurs the <see cref="WebSocketServerBase.OnError"/> event with the specified <see cref="string"/>. /// Occurs the <see cref="WebSocketServerBase.OnError"/> event with the specified <see cref="string"/>.
@ -423,12 +419,12 @@ namespace WebSocketSharp.Server {
/// <param name="message"> /// <param name="message">
/// A <see cref="string"/> that contains an error message. /// A <see cref="string"/> that contains an error message.
/// </param> /// </param>
protected virtual void Error(string message) protected virtual void Error (string message)
{ {
if (message.IsNullOrEmpty()) if (message.IsNullOrEmpty ())
return; return;
error(message); error (message);
} }
#endregion #endregion
@ -438,7 +434,7 @@ namespace WebSocketSharp.Server {
/// <summary> /// <summary>
/// Starts to receive the WebSocket connection requests. /// Starts to receive the WebSocket connection requests.
/// </summary> /// </summary>
public virtual void Start() public virtual void Start ()
{ {
if (!_selfHost || _listening) if (!_selfHost || _listening)
return; return;
@ -446,27 +442,27 @@ namespace WebSocketSharp.Server {
if (_secure && _cert == null) if (_secure && _cert == null)
{ {
var msg = "Secure connection requires a server certificate."; var msg = "Secure connection requires a server certificate.";
_logger.Error(msg); _logger.Error (msg);
error(msg); error (msg);
return; return;
} }
_listener.Start(); _listener.Start ();
startReceiveRequestThread(); startReceiveRequestThread ();
_listening = true; _listening = true;
} }
/// <summary> /// <summary>
/// Stops receiving the WebSocket connection requests. /// Stops receiving the WebSocket connection requests.
/// </summary> /// </summary>
public virtual void Stop() public virtual void Stop ()
{ {
if (!_selfHost || !_listening) if (!_selfHost || !_listening)
return; return;
_listener.Stop(); _listener.Stop ();
_receiveRequestThread.Join(5 * 1000); _receiveRequestThread.Join (5 * 1000);
_listening = false; _listening = false;
} }