/Network/HTTP/HTTPServer.cs |
@@ -14,43 +14,54 @@ |
public abstract class HTTPServer |
{ |
private int activeRequests; |
private readonly HttpListener HTTPListener = new HttpListener(); |
private readonly HttpListener HTTPListener = new HttpListener() |
{ |
AuthenticationSchemes = AuthenticationSchemes.None |
}; |
private int processedRequests; |
|
private readonly ManualResetEvent stopEvent = new ManualResetEvent(false); |
private readonly AutoResetEvent StopServerEvent = new AutoResetEvent(false); |
private readonly AutoResetEvent ServerStoppedEvent = new AutoResetEvent(false); |
|
public HashSet<string> Prefixes { get; set; } = new HashSet<string>(); |
|
public AuthenticationSchemes AuthenticationSchemes { get; set; } = AuthenticationSchemes.None; |
|
public bool IsRunning => HTTPListener.IsListening; |
|
public bool Start() |
public AuthenticationSchemes AuthenticationSchemes |
{ |
foreach (var prefix in Prefixes) |
get |
{ |
if (!HTTPListener.Prefixes.Contains(prefix)) |
HTTPListener.Prefixes.Add(prefix); |
return HTTPListener.AuthenticationSchemes; |
} |
set |
{ |
HTTPListener.AuthenticationSchemes = value; |
} |
} |
|
// Set up HTTP listener. |
HTTPListener.AuthenticationSchemes = AuthenticationSchemes; |
public bool IsRunning => HTTPListener.IsListening; |
|
public bool Start(IEnumerable<string> prefixes) |
{ |
// Do not start the HTTP server if it is already running. |
if (HTTPListener.IsListening) |
return false; |
|
// Add all prefixes. |
foreach (var prefix in prefixes) |
{ |
HTTPListener.Prefixes.Add(prefix); |
} |
|
// Do not bomb if the client disconnects. |
HTTPListener.IgnoreWriteExceptions = true; |
HTTPListener.Start(); |
var state = new HTTPServerCallbackState(HTTPListener); |
ThreadPool.QueueUserWorkItem(Listen, state); |
ThreadPool.QueueUserWorkItem(Listen, new HTTPServerCallbackState(HTTPListener)); |
return true; |
} |
|
public bool Stop() |
{ |
return stopEvent.Set(); |
StopServerEvent.Set(); |
ServerStoppedEvent.WaitOne(); |
HTTPListener.Prefixes.Clear(); |
return true; |
} |
|
private void Listen(object state) |
@@ -60,7 +71,7 @@ |
while (callbackState.Listener.IsListening) |
{ |
callbackState.Listener.BeginGetContext(ContextCallback, callbackState); |
var n = WaitHandle.WaitAny(new WaitHandle[] {callbackState.ContextRetrieved, stopEvent}); |
var n = WaitHandle.WaitAny(new WaitHandle[] {callbackState.ContextRetrieved, StopServerEvent}); |
|
if (n.Equals(1)) |
{ |
@@ -68,6 +79,8 @@ |
break; |
} |
} |
|
ServerStoppedEvent.Set(); |
} |
|
public abstract void ProcessHTTPContext(HttpListenerContext context); |