基於 TcpListener 實作極簡 HTTP 伺服器,加深理解 HTTP 協定。
static void Main(string[] args) {
IPAddress address = IPAddress.Loopback;
IPEndPoint endPoint = new IPEndPoint(address, 49152);
TcpListener server = new TcpListener(endPoint);
server.Start();
Console.WriteLine("開始監聽......");
while (true) {
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("已建立連線");
NetworkStream ns = client.GetStream();
Encoding utf8 = Encoding.UTF8;
byte[] request = new byte[4096];
int len = ns.Read(request, 0, 4096);
string reqStr = utf8.GetString(request);
Console.WriteLine(reqStr);
string statusLine = "HTTP/1.1 200 OK\r\n";
string responseBody = "<html><head><body><h1>hello world</h1></body></head></html>";
string header = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", responseBody.Length);
ns.Write(utf8.GetBytes(statusLine), 0, statusLine.Length);
ns.Write(utf8.GetBytes(header), 0, header.Length);
ns.Write(new byte[] { 13, 10 }, 0, 2); // CRLF
ns.Write(utf8.GetBytes(responseBody), 0, responseBody.Length);
client.Close();
if (Console.KeyAvailable) break;
}
server.Stop();
}
瀏覽器訪問 https://localhost:49152 即見回應。展示 HTTP 請求解析、狀態行、標頭、主體構建與發送的基本流程。