Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created February 18, 2015 12:23
Show Gist options
  • Save hagbarddenstore/fa735caa0efa15d134d8 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/fa735caa0efa15d134d8 to your computer and use it in GitHub Desktop.
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