與 IIS 上發佈網站相比,使用 HttpListener 編程的程序更加輕量化,易於發佈和更新。配合 Thread 或 Task 類也可知足必定的併發。html
https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httplistener?view=netframework-4.7.2編程
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Threading; using System.IO; //https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httplistener?view=netframework-4.7.2 namespace WebServer { class Program { static void Main(string[] args) { try { using (HttpListener listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:8888/"); listener.Start(); Console.WriteLine("開始監聽"); while (true) { try { HttpListenerContext context = listener.GetContext();//阻塞 HttpListenerRequest request = context.Request; string postData = new StreamReader(request.InputStream).ReadToEnd(); Console.WriteLine("收到請求:" + postData); HttpListenerResponse response = context.Response;//響應 string responseBody = "響應"; response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody); response.ContentType = "text/html; Charset=UTF-8"; //輸出響應內容 Stream output = response.OutputStream; using (StreamWriter sw = new StreamWriter(output)) { sw.Write(responseBody); } Console.WriteLine("響應結束"); } catch (Exception err) { Console.WriteLine(err.Message); } } } } catch (Exception err) { Console.WriteLine("程序異常,請從新打開程序:" + err.Message); } } } }