官术网_书友最值得收藏!

  • 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請求參數,我們就不能直接通過屬性訪問。

主站蜘蛛池模板: 沧州市| 闵行区| 汝阳县| 台中县| 鄂州市| 隆德县| 会东县| 射洪县| 赫章县| 贵港市| 固镇县| 博湖县| 宁远县| 滨州市| 龙门县| 金山区| 富源县| 宜君县| 丹东市| 汉川市| 合水县| 汾阳市| 宁明县| 米林县| 衡水市| 嘉兴市| 宁化县| 剑川县| 容城县| 阿鲁科尔沁旗| 渭源县| 普洱| 新龙县| 天峻县| 申扎县| 怀宁县| 舒兰市| 华宁县| 兰考县| 象山县| 荆州市|