Michal Habalcik

Michal Habalcik

  • NA
  • 3.5k
  • 2.3m

C# HttpListener not responding

Jun 17 2017 1:05 PM
Hi guys, I have some issues creating a local webserver using the HttpListener. When I use localhost uri (or 127.0.0.1), it works just fine and nicely responds to the requests.

However, when I add some madeup domain, like "whateverabc.com", the server is not responding to requests anymore and chrome is printing ERR_NAME_NOT_RESOLVED error.

What I am missing? Thanks!

public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;

public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");

if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

if (method == null)
throw new ArgumentException("method");

foreach (string s in prefixes)
_listener.Prefixes.Add(s);

_listener.IgnoreWriteExceptions = true;
_responderMethod = method;
_listener.Start();
}

public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }

public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { } // suppress any exceptions
finally
{
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}

public void Stop()
{
_listener.Stop();
_listener.Close();
}
}

static void Main(string[] args)
{
WebServer ws = new WebServer(SendResponse, "http://whateverabc.com:54785/");
ws.Run();
Console.WriteLine("A simple webserver. Press a key to quit.");
Console.ReadKey();
ws.Stop();
}

public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
}

Answers (4)