不知園友們看沒看上一篇博文,上篇將的是通過最底層的Socket(套接字)實現一個簡單的Web服務器,是不是感覺有點繁瑣,不要怕今天這篇博文就帶你們認識一個新的實現方法,就是使用HttpListener
為了進一步簡化Http協議的監聽器,.net為我們提供了HttpListener類,(為與命名空間System.Net).net在這個類中封裝了一系列的的處理Http協議的工作。
首先看一下MSDN中的定義:
注意:此類在 .NET Framework 2.0 版中是新增的。
提供一個簡單的、可通過編程方式控制的 HTTP 協議偵聽器。無法繼承此類。
用法:
public sealed class HttpListener : IDisposable
注意:該類只能在Win xp 或者win server 2003 以上的操作系統中才能使用,因為這個類必須使用Http.sys系統組件才能完成工作。
所以在使用前應該先判斷一下是否支持該類
// 檢查系統是否支持 if (!HttpListener.IsSupported) { throw new System.InvalidOperationException( "使用 HttpListener 必須為 Windows XP SP2 或 Server 2003 以上系統!"); }
下面羅列下本案例所用到的一些屬性方法
1. HttpListener.prefixes 獲取由此HttpListener對象處理的URI(統一資源標示符)前綴。
// 注意前綴必須以 / 正斜杠結尾 string[] prefixes = new string[] { "http://localhost:8080/" }; // 創建監聽器. HttpListener listener = new HttpListener(); // 增加監聽的前綴. foreach (string s in prefixes) { listener.Prefixes.Add(s); }
2. Start()方法 允許此實例接受傳入的請求。即開始監聽
3. Stop()方法 處理完所有當前排隊的請求后關閉HttpListener對象
4. GetContext()方法 等待傳入的請求接受到請求時返回 就如同上一篇的Socket實現服務器一樣 有一個Accept()方法他倆個差不多都是等待傳入的請求還有 一點就是GetContext()方法也會阻塞線程,當客戶端的請求到達時,返回一個HttpListenerContext對象,處理客戶端所發送過來的請求。
4.1 Request 獲取表示客戶端資源的HttpListenerRequest對象。
4.1.1 AcceptType 獲取客戶端接受到的MIME類型。
4.1.2 UserLanguages 獲取語言信息。
4.1.3 UserAgent 獲取客戶端提供的用戶代理。
4.1.4 Headers 獲取在請求中發送的標頭名稱/值對的集合 --->獲取HttpListenerRequest類沒有提供的一下屬性。
4.2 Response 該屬性獲得HttpListenerResponse對象,該對象將被發送到客戶端以響應客戶端的請求。
4.2.1 ContextLength64 獲取或設置響應中包括的正文數據的字節數。
4.2.2 ContextType 獲取或設置返回內容的 MIME 類型。
通過流的方式將響應報文體的內容發送給客戶端瀏覽器。
下面是本文源碼:
// 檢查系統是否支持 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();
通過HttpWatch看一下報文吧
看到報文后是不是和源碼中指定的一些屬性相同 啊
(*^__^*) 嘻嘻…… 本篇就到這里 ( ^_^ )/~~拜拜
要源碼的狂點啊 重要的不是運行結果是我上面給你們羅列的知識點哈