Created
March 4, 2015 19:44
-
-
Save jltrem/943581107d1d1a168d18 to your computer and use it in GitHub Desktop.
http server that processes requests and sends responses with cookies
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Text; | |
using System.Threading; | |
namespace Whatever | |
{ | |
public class HttpResponseData | |
{ | |
public string Output { get; set; } | |
public CookieCollection Cookies { get; set; } | |
public HttpResponseData() | |
{ | |
Output = ""; | |
Cookies = new CookieCollection(); | |
} | |
} | |
public class LittleHttpServer | |
{ | |
private readonly HttpListener _listener = new HttpListener(); | |
private readonly Func<HttpListenerRequest, HttpResponseData> _responderResponderMethod; | |
public LittleHttpServer(string[] prefixes, Func<HttpListenerRequest, HttpResponseData> responderMethod) | |
{ | |
if (!HttpListener.IsSupported) | |
{ | |
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later."); | |
} | |
// e.g., "http://localhost:8080/api/" | |
if (prefixes == null || prefixes.Length == 0) | |
{ | |
throw new ArgumentException("prefixes"); | |
} | |
// a responder method is required | |
if (responderMethod == null) | |
{ | |
throw new ArgumentException("responderMethod"); | |
} | |
foreach (string s in prefixes) | |
{ | |
_listener.Prefixes.Add(s); | |
} | |
_responderResponderMethod = responderMethod; | |
_listener.Start(); | |
} | |
public LittleHttpServer(Func<HttpListenerRequest, HttpResponseData> method, params string[] prefixes) | |
: this(prefixes, method) | |
{ | |
} | |
public void Run() | |
{ | |
ThreadPool.QueueUserWorkItem(o => | |
{ | |
try | |
{ | |
while (_listener.IsListening) | |
{ | |
ThreadPool.QueueUserWorkItem(c => | |
{ | |
var ctx = c as HttpListenerContext; | |
if (ctx != null) | |
{ | |
try | |
{ | |
HttpResponseData data = _responderResponderMethod(ctx.Request); | |
byte[] buf = Encoding.UTF8.GetBytes(data.Output); | |
ctx.Response.ContentLength64 = buf.Length; | |
// set any cookies that were provided by the responder method | |
foreach (var x in data.Cookies.OfType<Cookie>()) | |
{ | |
ctx.Response.SetCookie(x); | |
} | |
// write the output text that was provided by the responder method | |
ctx.Response.OutputStream.Write(buf, 0, buf.Length); | |
} | |
catch | |
{ | |
} | |
finally | |
{ | |
ctx.Response.OutputStream.Close(); | |
} | |
} | |
}, _listener.GetContext()); | |
} | |
} | |
catch | |
{ | |
} | |
}); | |
} | |
public void Stop() | |
{ | |
_listener.Stop(); | |
_listener.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment