Skip to content

Instantly share code, notes, and snippets.

@khoahuynhdev
Last active July 20, 2022 11:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khoahuynhdev/71afd210af5dbc4030605290e28b05d8 to your computer and use it in GitHub Desktop.
Save khoahuynhdev/71afd210af5dbc4030605290e28b05d8 to your computer and use it in GitHub Desktop.
simple HttpListener in C#
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace HttpListenerExample
{
class Program
{
public static HttpListener listener;
public static string url = @"http://localhost:3000/";
public static int pageViews = 0;
public static int requestCount = 0;
public static string pageData =
"<!DOCTYPE>" +
"<html>" +
" <head>" +
" <title>HttpListener</title>" +
" </head>" +
" <body>" +
" <p>Page Views: {0}</p>" +
" <form method=\"post\" action=\"shutdown\">" +
" <input type=\"submit\" value=\"Shutdown\" {1}>" +
" </form>" +
" </body>" +
"</html>";
public static async Task HandleIncomingConnections()
{
bool runServer = true;
// while a user haven't visitted the shutdown url, keep on handling request
while (runServer)
{
// will wait here until we hear from a connection
HttpListenerContext ctx = await listener.GetContextAsync();
// peel out the requests and response objects
HttpListenerRequest req = ctx.Request;
HttpListenerResponse resp = ctx.Response;
// print out some info about the request
Console.WriteLine("Request #{0}", ++requestCount);
Console.WriteLine(req.Url.ToString());
Console.WriteLine(req.HttpMethod);
Console.WriteLine(req.UserHostName);
Console.WriteLine(req.UserAgent);
Console.WriteLine(req.UserHostAddress);
Console.WriteLine();
// if 'shutdown' url requested with POST, then shutdown the server after serving the page
if (req.HttpMethod == "POST" && req.Url.AbsolutePath == @"/shutdown")
{
Console.WriteLine("shutdown the server");
runServer = false;
continue;
}
// make sure don't increse view page count if favicon.ico is requested
if (req.Url.AbsolutePath != @"/favicon.ico")
pageViews++;
// write the response info
string disableSubmit = !runServer ? "disable" : "";
byte[] data = Encoding.UTF8.GetBytes(String.Format(pageData, pageViews, disableSubmit));
resp.ContentType = "text/html";
resp.ContentEncoding = Encoding.UTF8;
resp.ContentLength64 = data.LongLength;
// write out to the response stream (async) and close
await resp.OutputStream.WriteAsync(data, 0, data.Length);
resp.Close();
//Thread.Sleep(TimeSpan.FromSeconds(15));
}
}
static void Main(string[] args)
{
// create a http server and start listening
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
Console.WriteLine("Listening for connections on {0}", url);
// handle requests
Task listenTask = HandleIncomingConnections();
listenTask.GetAwaiter().GetResult();
// close the listener
listener.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment