HttpListener提供一個簡單的、可通過編程方式控制的 HTTP 協議偵聽器。通過它可以很容易的提供一些Http服務,而無需啟動IIS這類大型服務程序。
注意:該類僅在運行 Windows XP SP2 或 Windows Server 2003 操作系統的計算機上可用。
使用Http服務一般步驟如下:
-
創建一個HTTP偵聽器對象並初始化
-
添加需要監聽的URI 前綴
-
開始偵聽來自客戶端的請求
-
處理客戶端的Http請求
-
關閉HTTP偵聽器
其中3,4兩步可以循環處理,以提供多客戶多次請求的服務。
創建一個HTTP偵聽器對象
創建HTTP偵聽器對象只需要新建一個HttpListener對象即可。
HttpListener listener = newHttpListener();
初始化需要經過如下兩步
- 添加需要監聽的URL范圍至listener.Prefixes中,可以通過如下函數實現: listener.Prefixes.Add(prefix) //prefix必須以'/'結尾
- 調用listener.Start()實現端口的綁定,並開始監聽客戶端的需求。
接受HTTP請求
在.net2.0中,通過HttpListenerContext對象提供對HttpListener類使用的請求和響應對象的訪問。
獲取HttpListenerContext的最簡單方式如下:
HttpListenerContext context = listener.GetContext();
該方法將阻塞調用函數至接收到一個客戶端請求為止,如果要提高響應速度,可使用異步方法listener.BeginGetContext()來實現HttpListenerContext對象的獲取。
處理HTTP請求
獲取HttpListenerContext后,可通過Request屬性獲取表示客戶端請求的對象,通過Response屬性取表示 HttpListener 將要發送到客戶端的響應的對象。
HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response;
這里的HttpListenerRequest對象和HttpListenerResponse對象和Asp中的Request和Response的使用方式類似,這里就不多說了,具體的使用可以參看下面的例子。
關閉HTTP偵聽器
通過調用listener.Stop()函數即可關閉偵聽器,並釋放相關資源
代碼示例:
using System; using System.Collections.Generic; using System.Text;
using System.Net;
namespace ConsoleApplication1 { class Program { staticvoid Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost/"); //添加需要監聽的url范圍 listener.Start(); //開始監聽端口,接收客戶端請求 Console.WriteLine("Listening...");
//阻塞主函數至接收到一個客戶端請求為止 HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response;
string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); //對客戶端輸出相應信息. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); //關閉輸出流,釋放相應資源 output.Close();
listener.Stop(); //關閉HttpListener } } }
該程序功能比較簡單,首先創建了一個HTTP偵聽器,使其實現對"http://localhost/time/"域的服務,接收到一個遠程請求時,將當前時間轉換為字符串輸出給客戶端,然后關閉偵聽器。