Skip to content

Instantly share code, notes, and snippets.

@therealjohn
Created January 10, 2018 03:46
Show Gist options
  • Save therealjohn/6ba5cb2e55ddd1213732a6ffbbdab91e to your computer and use it in GitHub Desktop.
Save therealjohn/6ba5cb2e55ddd1213732a6ffbbdab91e to your computer and use it in GitHub Desktop.
public class Program
{
static HttpListener listener;
static HttpListenerContext context;
private const int bufferSize = 4096;
public static void Main()
{
listener = new HttpListener("http", 8500);
listener.Start();
new Thread(() => {
while (true)
{
try
{
context = listener.GetContext();
Process(context);
}
catch (Exception ex)
{
Debug.Print(ex.Message);
Debug.Print(ex.StackTrace);
}
}
}).Start();
while(true)
{
Thread.Sleep(5000);
Debug.Print("Still Active");
}
}
private static void Process(HttpListenerContext context)
{
Debug.Print("Received " + context.Request.HttpMethod + " - " + context.Request.RawUrl);
context.Response.StatusCode = (int)HttpStatusCode.OK;
WriteOutputStream(Encoding.UTF8.GetBytes("Ok"));
}
private static void WriteOutputStream(byte[] data)
{
context.Response.ContentLength64 = data.Length;
using (context.Response.OutputStream)
{
int i = 0;
byte[] buffer = new byte[bufferSize];
while (i * bufferSize <= data.Length)
{
int min = Min(bufferSize, data.Length - (i * bufferSize));
Array.Copy(data, i * bufferSize, buffer, 0, min);
context.Response.OutputStream.Write(buffer, 0, min);
i++;
}
context.Response.OutputStream.Flush();
}
}
private static int Min(int a, int b)
{
if (a <= b)
return a;
else
return b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment