自己實現簡單Web伺服器,支援GET POST請求

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

最近項目上遇到一個需求,最後想到的解決方案是自己實現一個web伺服器去處理請求,然後再將資訊發送到另外一個程式。然後返回處理之後的結果呈現出來。

現在我就來分享一下如何?的。

 

通過.NET 為我們提供的HttpListener類實現對Http協議的處理,實現簡單的web伺服器。

注意:此類在 .NET Framework 2.0 版中是新增的。所以支援.NET Framework 2.0以上版本。該類僅在運行 Windows XP SP2 或 Windows Server 2003 作業系統的電腦上可用。

引用命名空間:using System.Net;

使用Http服務一般步驟如下:

  1. 建立一個HTTP接聽程式對象並初始化
  2. 開始偵聽來自用戶端的請求
  3. 處理用戶端的Http請求
  4. 關閉HTTP接聽程式

建立一個HTTP接聽程式對象

建立HTTP接聽程式對象只需要建立一個HttpListener對象即可。

HttpListener listener = new HttpListener();

  

初始化需要經過如下兩步

    1. 添加需要監聽的URL範圍至listener.Prefixes中,可以通過如下函數實現:
      listener.Prefixes.Add("http://127.0.0.1:8080/")    //必須以‘/‘結尾
      多個的話可以採用迴圈添加。
    2. 調用listener.Start()實現連接埠的綁定,並開始監聽用戶端的需求。

 

偵聽來自用戶端的請求

 這裡有2種方式可以偵聽HTTP請求,擷取HttpListenerContext的最簡單方式如下:

HttpListenerContext context = listener.GetContext();

該方法將阻塞調用函數至接收到一個用戶端請求為止,如果要提高響應速度,可使用非同步方法呼叫listener.BeginGetContext()來實現HttpListenerContext對象的擷取。

我使用的是非同步方式實現對HttpListenerContext對象的擷取。

 

處理用戶端的HTTP請求

擷取HttpListenerContext後,可通過Request屬性擷取表示用戶端請求的對象,通過Response屬性取表示 HttpListener 將要發送到用戶端的響應的對象。

HttpListenerRequest request = context.Request;HttpListenerResponse response = context.Response;

 

關閉HTTP接聽程式

通過調用listener.Stop()函數即可關閉接聽程式,並釋放相關資源

 

實現GET POST請求處理

GET請求比較簡單,直接通過 request.QueryString["linezero"]; QueryString就可以實現擷取參數。

POST請求由於HttpListener 不提供實現,需要自己做處理。在下面相關代碼中會貼出方法。

 

相關代碼:

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.IO;namespace WebConsole{    class Program    {        static HttpListener sSocket;        static void Main(string[] args)        {            sSocket = new HttpListener();            sSocket.Prefixes.Add("http://127.0.0.1:8080/");            sSocket.Start();            sSocket.BeginGetContext(new AsyncCallback(GetContextCallBack), sSocket);            Console.WriteLine("已啟動監聽,訪問http://127.0.0.1:8080/");            Console.ReadKey();        }                static void GetContextCallBack(IAsyncResult ar)        {            try            {                sSocket = ar.AsyncState as HttpListener;                HttpListenerContext context = sSocket.EndGetContext(ar);                //再次監聽請求                sSocket.BeginGetContext(new AsyncCallback(GetContextCallBack), sSocket);                //處理請求                string a = Request(context.Request);                //輸出請求                Response(context.Response, a);            }            catch { }        }        /// <summary>        /// 處理輸入參數        /// </summary>        /// <param name="request"></param>        /// <returns></returns>        static string Request(HttpListenerRequest request)        {            string temp = "welcome to linezero!";            if (request.HttpMethod.ToLower().Equals("get"))             {                //GET請求處理                if (!string.IsNullOrEmpty(request.QueryString["linezero"]))                    temp = request.QueryString["linezero"];            }            else if (request.HttpMethod.ToLower().Equals("post"))             {                //這是在POST請求時必須傳參的判斷預設注釋掉                //if (!request.HasEntityBody)                 //{                //    temp = "請傳入參數";                //    return temp;                //}                //POST請求處理                Stream SourceStream = request.InputStream;                byte[] currentChunk = ReadLineAsBytes(SourceStream);                //擷取資料中有空白符需要去掉,輸出的就是post請求的參數字串 如:username=linezero                temp = Encoding.Default.GetString(currentChunk).Replace("", "");            }                        return temp;        }        static byte[] ReadLineAsBytes(Stream SourceStream)        {            var resultStream = new MemoryStream();            while (true)            {                int data = SourceStream.ReadByte();                resultStream.WriteByte((byte)data);                if (data <= 10)                    break;            }            resultStream.Position = 0;            byte[] dataBytes = new byte[resultStream.Length];            resultStream.Read(dataBytes, 0, dataBytes.Length);            return dataBytes;        }        /// <summary>        /// 輸出方法        /// </summary>        /// <param name="response">response對象</param>        /// <param name="responseString">輸出值</param>        /// <param name="contenttype">輸出類型預設為json</param>        static void Response(HttpListenerResponse response, string responsestring, string contenttype = "application/json")        {            response.StatusCode = 200;            response.ContentType = contenttype;            response.ContentEncoding = Encoding.UTF8;            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();        }    }}
View Code

 

 

 

最後啟動程式,在地址欄裡輸入http://127.0.0.1:8080 就可以訪問了。

 

如果你覺得本文對你有協助,請點擊“推薦”,謝謝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.