Quick and Easy HttpListener

Tags

,

Today is Sunday March 13, and my day off; however tomorrow I know I’ll be testing a client making requests, so why not make myself a nice simple web server ?

looking up MSDN for Http.Net, well, there it is HttpListener.  let me change the title of this blog post Smile

Its API is well documented and all….

so, what do I need? , I need my server to return certain responses base on the request Uri.  The concerned requested Uri Sleeping half-moon and their simple data (strings) to be return shall come from a text file.  Each Uri and its returned data will occupy one line in the text document separated by “::”.

<uri> :: <data>

example :

http://127.0.0.1:8080/bnj/ :: afasdfas adsfafafdasfa

http://127.0.0.1:8080/op/ :: 69

 

everything look nice, but I am getting an access denied exception; whats going on ? let me run VS 2013 as admin and google it.  well, same exception, but this time google  and bing tell me to run the following commands

netsh http add

netsh help command gives an nice example on using it; nice;

finally everything is working. I can reach into the code with the browser and fiddler. nice job and all that under 1 hour. Smile

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Diagnostics;

namespace httSvr
{
class Program
{
//// netsh http delete urlacl http://+:8080/
//// netsh http add url=http://+:8080/ user=Everyone
//// run as admin
private static Dictionary<string, string> _dict = new Dictionary<string, string>();
public static System.Threading.ManualResetEventSlim _mnlRst = new System.Threading.ManualResetEventSlim(false);
private static bool _keepRunning = true;
static void Main(string[] args)
{

using(var strm = System.IO.File.OpenText(args[0]))
{
while(strm.Peek() >= 0)
{
var str = strm.ReadLine();
var data = str.Split(new []{"::"}, StringSplitOptions.None);
_dict[data[0].Trim()] = data[1];
}
}
var srvr = new HttpListener();
Console.WriteLine(String.Format( "Current thread id : {0}" , System.Threading.Thread.CurrentThread.ManagedThreadId));
var process = CreateProcess();
process.Start();

foreach(var kvp in _dict)
{
process.StandardInput.WriteLine("netsh http delete urlacl {0}", kvp.Key);
process.StandardInput.WriteLine("netsh http add url={0} user=Everyone", kvp.Key);
srvr.Prefixes.Add(kvp.Key);

}

//srvr.Prefixes.Add("http://www.localhost:8080/bnj");

//Task.Run( () =>
// {
srvr.Start();
// _mnlRst.Set();
//});

//_mnlRst.Wait();
Console.WriteLine("Begin processing request");
Task.Run(() => {
while (_keepRunning )
{
var Isnc = srvr.BeginGetContext(new AsyncCallback((IAsyncResult iAsnycRslt) =>
{

Console.WriteLine(String.Format("Current thread processing request named : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId));
var context = srvr.EndGetContext(iAsnycRslt);

var requestUri = context.Request.Url;

if (_dict.Keys.Contains(requestUri.OriginalString))
{
var dataSrce = _dict[requestUri.OriginalString];

var data = Encoding.Default.GetBytes(dataSrce);

context.Response.ContentLength64 = data.LongLength;
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();

Console.WriteLine("response send to client :)");
}
else
{
Console.WriteLine("Key not found : {0}", requestUri.OriginalString);
}

}), srvr);

Isnc.AsyncWaitHandle.WaitOne();

/* var context = srvr.GetContext();

var requestUri = context.Request.Url;
var dataSrce = _dict[requestUri.OriginalString];

var data = Encoding.Default.GetBytes(dataSrce);

context.Response.ContentLength64 = data.LongLength;
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();

Console.WriteLine("response send to client :)");*/
}
});
Console.WriteLine("Press Enter to exit :)");
Console.ReadLine();
_keepRunning = false;
System.Threading.Thread.Sleep(600);
srvr.Stop();
}

private static Process CreateProcess()
{
var processStartInfo = new ProcessStartInfo()
{
FileName = "cmd.exe",
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false
};

return new Process() { StartInfo = processStartInfo };
}
}
}