首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

教你使用 ASP.NET 撰寫簡易 Web 伺服器

     編輯:關於ASP.NET

基於 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 請求解析、狀態行、標頭、主體構建與發送的基本流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved