基於HttpListener的web服務器

 

 

寫在前面

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

HttpListener

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

複製代碼
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/ 博客版權:若是文中有不妥或者錯誤的地方還望高手的你指出,以避免誤人子弟。若是以爲本文對你有所幫助不如【推薦】一下!若是你有更好的建議,不如留言一塊兒討論,共同進步! 再次感謝您耐心的讀完本篇文章。
相關文章
相關標籤/搜索