基於HttpListener的web服務器


 

 

寫在前面

前面兩篇文章分別介紹了基於原始socket的web服務器和基於tcpListener的web服務器,本篇文章將繼續介紹另外一種基於HttpListener的。

HttpListener

HttpListener進一步的簡化了Http協議的監聽,僅需通過字符串的方法提供監聽的地址和端口號以及虛擬路徑,就可以開始監聽工作了。

復制代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpListenerWebServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //httpListener提供一個簡單,可通過編程方式控制的Http協議偵聽器。此類不能被繼承。
            if (!HttpListener.IsSupported)
            {
                //該類只能在Windows xp sp2或者Windows server 200 以上的操作系統中才能使用,因為這個類必須使用Http.sys系統組件才能完成工作
                //。所以在使用前應該先判斷一下是否支持該類
                Console.WriteLine("Windows xp sp2 or server 2003 is required to use the HttpListener class");
            }
            //設置前綴,必須以‘/’結尾
            string[] prefixes = new string[] { "http://localhost:8888/" };
            //初始化監聽器
            HttpListener listener = new HttpListener();
            //將前綴添加到監聽器
            foreach (var item in prefixes)
            {
                listener.Prefixes.Add(item);
            }
            //判斷是否已經啟動了監聽器,如果沒有則開啟
            if (!listener.IsListening)
            {
                listener.Start();
            }
            //提示
            Console.WriteLine("服務器已經啟動,開始監聽....");
            while (true)
            {
                //等待傳入的請求,該方法將阻塞進程,直到收到請求
                HttpListenerContext context = listener.GetContext();
                //取得請求的對象
                HttpListenerRequest request = context.Request;
                //打印狀態行 請求方法,url,協議版本
                Console.WriteLine("{0} {1} HTTP/{2}\r\n", request.HttpMethod, request.RawUrl, request.ProtocolVersion);
                //打印接收類型
                Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
                //打印接收語言
                Console.WriteLine("Accept-Language: {0}", string.Join(",", request.UserLanguages));
                //打印編碼格式
                Console.WriteLine("Accept-Encoding: {0}", string.Join(",", request.Headers["Accept-Encoding"]));
                //客戶端引擎
                Console.WriteLine("User-Agent: {0}", string.Join(",", request.UserAgent));
                //是否長連接
                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 responseBody = "<html><head><title>這是一個web服務器的測試</title></head><body><h1>Hello World.</h1></body></html>";
                //設置響應頭部內容,長度及編碼
                response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody);
                response.ContentType = "text/html; Charset=UTF-8";
                //輸出響應內容
                System.IO.Stream output = response.OutputStream;
                System.IO.StreamWriter sw = new System.IO.StreamWriter(output);
                sw.Write(responseBody);
                sw.Dispose();
                break;
            }
            //關閉服務器
            listener.Close();
            Console.Read();

        }
    }
}
復制代碼

啟動服務器,並在瀏覽器中輸入:http://localhost:8888/ 回車

總結

在使用httplistener時,我們可以通過對象的屬性獲取到請求和響應的參數。

  • 博客地址:http://www.cnblogs.com/wolf-sun/ 
    博客版權:如果文中有不妥或者錯誤的地方還望高手的你指出,以免誤人子弟。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起討論,共同進步! 再次感謝您耐心的讀完本篇文章。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM