Created
February 18, 2015 12:23
-
-
Save hagbarddenstore/fa735caa0efa15d134d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Company.HttpServer | |
{ | |
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Threading; | |
public class Server | |
{ | |
private static readonly ConcurrentDictionary<string, Instance> Instances = new ConcurrentDictionary<string, Instance>(); | |
public static void ListenAndServe(string url, Handler handler) | |
{ | |
if (!Instances.TryAdd(url, new Instance(url, handler))) | |
{ | |
throw new NotSupportedException(); | |
} | |
Instances[url].Start(); | |
} | |
public static void Stop(string url) | |
{ | |
Instance instance; | |
if (!Instances.TryGetValue(url, out instance)) | |
{ | |
throw new KeyNotFoundException(); | |
} | |
instance.Stop(); | |
} | |
private class Instance | |
{ | |
private readonly AutoResetEvent _waitHandle = new AutoResetEvent(false); | |
private readonly string _url; | |
private readonly Handler _handler; | |
private HttpListener _listener; | |
private bool _running = true; | |
public Instance(string url, Handler handler) | |
{ | |
_handler = handler; | |
_url = url; | |
} | |
public void Start() | |
{ | |
new Thread(state => | |
{ | |
using (_listener = new HttpListener()) | |
{ | |
_listener.Prefixes.Add(_url); | |
_listener.Start(); | |
while (_running) | |
{ | |
var result = _listener.BeginGetContext(Process, null); | |
result.AsyncWaitHandle.WaitOne(); | |
} | |
_listener.Stop(); | |
} | |
}).Start(); | |
} | |
public void Stop() | |
{ | |
_running = false; | |
} | |
private static void HandleRequest(HttpListenerContext context, Handler handler) | |
{ | |
var response = new ResponseWriter(context.Response); | |
var request = new Request(context.Request); | |
handler.Serve(response, request); | |
context.Response.Close(); | |
} | |
private void Process(IAsyncResult result) | |
{ | |
var context = _listener.EndGetContext(result); | |
HandleRequest(context, _handler); | |
context.Response.Close(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment