Skip to content

Instantly share code, notes, and snippets.

@1f0
Created August 5, 2019 07:00
Show Gist options
  • Save 1f0/748faf1948ef92d69d8b855e1a2a0816 to your computer and use it in GitHub Desktop.
Save 1f0/748faf1948ef92d69d8b855e1a2a0816 to your computer and use it in GitHub Desktop.
using System;
using System.Net;
using System.Text;
using System.Threading;
namespace SimpleHttp
{
// reference: https://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server
class SimpleHttpServer
{
private readonly HttpListener _server = new HttpListener();
private readonly Func<HttpListenerRequest, string> _respondMethod;
public SimpleHttpServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException("HttpListener not supported.");
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("Prefixs");
_respondMethod = method ?? throw new ArgumentNullException("method");
foreach (var s in prefixes)
_server.Prefixes.Add(s);
_server.Start();
}
public SimpleHttpServer(Func<HttpListenerRequest, string> method, params string[] prefixes) : this(prefixes, method) { }
public void Run()
{
while (_server.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
var resp = _respondMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(resp);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ctx.Response.OutputStream.Close();
}
}, _server.GetContext());
}
}
public void Stop()
{
_server.Stop(); // pause
_server.Close();// pending request not completed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment