- ASP.NET本質論
- 郝冠軍
- 720字
- 2018-12-31 19:25:13
1.2.3 基于HttpListener的Web服務器
為了進一步簡化 HTTP協議的監聽器,.NET在命名空間System.NET中提供了HttpListener類。伴隨這個對象,.NET提供了一系列相關對象封裝了HTTP的處理工作。注意,這個類使用HTTP.sys系統組件完成工作,所以,只有在Windows XP SP2或者Server 2003以上的操作系統中才能使用。
HttpListener類進一步簡化了監聽操作,僅需通過字符串的方法提供監聽的地址、端口號以及虛擬路徑,就可以開始監聽工作。
開始監聽后,GetContext方法將阻塞線程,當客戶端的請求到達之后,HttpListener 返回一個HttpListenerContext對象作為處理客戶端請求的總代理,通過代理對象的Request屬性,我們可以得到一個類型為HttpListenerRequest的代表請求參數的對象,這個對象將大多數請求參數進行了對象化,所以,我們可以通過它提供的一系列屬性來獲取請求參數。例如HttpListenerRequest的HttpMethod屬性就提供了請求的方法類型。通過代理的Response屬性,可以得到一個類型為HttpListenerResponse的回應處理對象,這個對象將回應的數據和操作進行了封裝,使得我們大幅度簡化了回應的編程工作量,工作過程如下所示:
// 檢查系統是否支持 if (!HttpListener.IsSupported) { throw new System.InvalidOperationException( " 使用 HttpListener 必須為 Windows XP SP2 或 Server 2003 以上系統! "); } // 注意前綴必須以/ 正斜杠結尾 string[]prefixes = new string[]{"http://localhost:49152/"}; // 創建監聽器. HttpListener listener = new HttpListener(); // 增加監聽的前綴. foreach (string s in prefixes) { listener.Prefixes.Add(s); } // 開始監聽 listener.Start(); Console.WriteLine(" 監聽中..."); while (true) { // 注意: GetContext 方法將阻塞線程,直到請求到達 HttpListenerContext context = listener.GetContext(); // 取得請求對象 HttpListenerRequest request = context.Request; Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl); Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes)); Console.WriteLine("Accept-Language: {0}", string.Join(",",request.UserLanguages)); Console.WriteLine("User-Agent: {0}", request.UserAgent); Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]); Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" :"close"); Console.WriteLine("Host: {0}", request.UserHostName); Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]); // 取得回應對象 HttpListenerResponse response = context.Response; // 構造回應內容 string responseString = @"<html> <head><title> From HttpListener Server</title></head> <body><h1>Hello, world. </h1></body> </html> "; //設置回應頭部內容,長度,編碼 response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseString); response.ContentType = "text/html; charset=UTF-8"; // 輸出回應內容 System.IO.Stream output = response.OutputStream; System.IO.StreamWriter writer = new System.IO.StreamWriter(output); writer.Write(responseString); // 必須關閉輸出流 writer.Close(); if (Console.KeyAvailable) break; } // 關閉服務器 listener.Stop();
在使用HttpListener的時候,常用的請求和回應參數都變成了對象的屬性,大幅度降低了編程的工作量。但是,大多數的參數還是需要通過Headers 索引器來訪問的,就像上例中的Accept-Encoding請求參數,我們就不能直接通過屬性訪問。
推薦閱讀
- 極簡算法史:從數學到機器的故事
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- C語言程序設計(第3版)
- Learning Spring 5.0
- Cocos2d-x游戲開發:手把手教你Lua語言的編程方法
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- jQuery從入門到精通 (軟件開發視頻大講堂)
- Java深入解析:透析Java本質的36個話題
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- Web程序設計(第二版)
- FFmpeg入門詳解:音視頻原理及應用
- Python完全自學教程
- Serverless架構
- Python算法詳解
- HTML5從入門到精通(第4版)