簡単なHTTPサーバを作る
.NETではSystem.Net名前空間のHttpListenerクラスを
使うことによって簡易HTTPサーバを自作することができる。
HttpListener Class (System.Net) | Microsoft Docs
HttpListenerContext Class (System.Net) | Microsoft Docs
HttpListenerRequest Class (System.Net) | Microsoft Docs
HttpListenerResponse Class (System.Net) | Microsoft Docs
MediaTypeNames Class (System.Net.Mime) | Microsoft Docs
static void Main(string[] args) { string prefix = "http://*:34567/"; if (!HttpListener.IsSupported) { Console.WriteLine("Not Supported!"); return; } HttpListener hl = new HttpListener(); hl.Prefixes.Add(prefix); hl.Start(); while (true) { HttpListenerContext context = hl.GetContext(); HttpListenerRequest req = context.Request; HttpListenerResponse res = context.Response; res.StatusCode = (int)HttpStatusCode.OK; res.ContentType = MediaTypeNames.Text.Html; res.ContentEncoding = Encoding.UTF8; StreamWriter sw = new StreamWriter(res.OutputStream); sw.WriteLine("this is server program's response."); sw.Flush(); res.close(); } }
これで起動したクライアントのブラウザでポート34567番にアクセスすると、
this is server program's response. と表示される。