public void Run() { ThreadPool.QueueUserWorkItem(o => { //Console.WriteLine("Webserver running..."); try { while (_listener.IsListening) { ThreadPool.QueueUserWorkItem(c => { var ctx = c as HttpListenerContext; var response = HttpResponse.Blank; try { response = _responderMethod(ctx.Request); } catch (HttpFileNotFoundException) { ctx.Response.StatusCode = 404; response = new HttpResponse() { Content = "File Not Found", Mime = "text/html" }; } catch (Exception) { ctx.Response.StatusCode = 500; response = new HttpResponse() { Content = "Server Error", Mime = "text/html" }; } finally { var buf = Encoding.UTF8.GetBytes(response.Content); ctx.Response.ContentLength64 = buf.Length; ctx.Response.ContentType = response.Mime; ctx.Response.OutputStream.Write(buf, 0, buf.Length); ctx.Response.OutputStream.Flush(); ctx.Response.OutputStream.Close(); } }, _listener.GetContext()); } } catch { // ignored } // suppress any exceptions }); }
private HttpResponse HttpRequest(HttpListenerRequest arg) { var path = arg.Url.LocalPath.TrimStart('/'); if (String.IsNullOrWhiteSpace(path)) { path = "client.html"; } HttpResponse response; try { response = new HttpResponse() { Content = _htdocs[path], Mime = MimeTypeMap.GetMimeType(Path.GetExtension(path)) }; } catch { throw new HttpFileNotFoundException(); } return response; }