C# 兩種方法實現HTTP協議迷你服務器


 本文以兩種稍微有差別的方式用C#語言實現HTTP協議的服務器類,之所以寫這些,也是為了自己能更深刻了解HTTP底層運作。

 

要完成高性能的Web服務功能,通常都是需要寫入到服務,如IIS,Apache Tomcat,

但是眾所周知的Web服務器配置的復雜性,如果我們只是需要一些簡單的功能,安裝這些組件看起來就沒多大必要。

我們需要的是一個簡單的HTTP類,可以很容易地嵌入到簡單的Web請求的服務,加到自己的程序里。

 

 

實現方法一:

.net框架下有一個簡單但很強大的類HttpListener。

這個類幾行代碼就能完成一個簡單的服務器功能。

雖然以下內容在實際運行中幾乎毫無價值,但是也不失為理解HTTP請求過程的細節原理的好途徑。

    HttpListener httpListener = new HttpListener();

    httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
    httpListener.Prefixes.Add("http://localhost:8080/");
    httpListener.Start();
    new Thread(new ThreadStart(delegate
    {
        while (true)
        { 
            HttpListenerContext httpListenerContext = httpListener.GetContext();
            httpListenerContext.Response.StatusCode = 200;  //設置返回給客服端http狀態代碼

using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream)) { writer.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>測試服務器</title></head><body>"); writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hello</p></div>"); writer.WriteLine("<ul>"); writer.WriteLine("</ul>"); writer.WriteLine("</body></html>"); } } })).Start();

如果你運用的好,舉一反三的話,這樣一個簡單的類可能會收到意想不到的效果,

但是由於HttpListener這個類對底層的完美封裝,導致對協議的控制失去靈活性,因此我想大型服務器程序里肯定不會用這個類去實現。

因此如果必要的話,自己用Tcp協議再去封裝一個類,以便更好的控制服務運行狀態。

 

 

實現方法二:

這個方法是一個老外分享的,雖然文件內容看起來很亂,其實邏輯很強很有條理。讓我們來分析一下實現過程:

通過子類化HttpServer和兩個抽象方法handlegetrequest和handlepostrequest提供實現…

public class MyHttpServer : HttpServer {
    public MyHttpServer(int port)
        : base(port) {
    }
    public override void handleGETRequest(HttpProcessor p) {
        Console.WriteLine("request: {0}", p.http_url);
        p.writeSuccess();
        p.outputStream.WriteLine("<html><body><h1>test server</h1>");
        p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
        p.outputStream.WriteLine("url : {0}", p.http_url);
        
        p.outputStream.WriteLine("<form method=post action=/form>");
        p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
        p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
        p.outputStream.WriteLine("</form>");
    }
    
    public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) {
        Console.WriteLine("POST request: {0}", p.http_url);
        string data = inputData.ReadToEnd();
        
        p.outputStream.WriteLine("<html><body><h1>test server</h1>");
        p.outputStream.WriteLine("<a href=/test>return</a><p>");
        p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
    }
}

 如果你能夠順利編譯和運行附件中的項目,就你應該能夠用Web瀏覽器輸入Http://localhost:8080/,打開就可以看上面的簡單的HTML頁面渲染。

 

讓我們看看怎么具體是怎么實現的吧~!

    這個簡單的Web服務器可以分解為兩個部分。

HttpServer類開啟了一個指定輸入端口的TcpListener實例,使用accepttcpclient()用於循環處理傳入的TCP連接請求。

這是處理傳入的TCP連接的第一步。

當傳入的請求到達已知的指定端口,這個接受過程會創建一個新的服務器與客戶端端口配對,用於服務器語言客戶端的連接通信。、

View Code 

public abstract class HttpServer {

    protected int port;
    TcpListener listener;
    bool is_active = true;
   
    public HttpServer(int port) {
        this.port = port;
    }
    
    public void listen() {
        listener = new TcpListener(port);
        listener.Start();
        while (is_active) {                
            TcpClient s = listener.AcceptTcpClient();
            HttpProcessor processor = new HttpProcessor(s, this);
            Thread thread = new Thread(new ThreadStart(processor.process));
            thread.Start();
            Thread.Sleep(1);
        }
    }
    
    public abstract void handleGETRequest(HttpProcessor p);
    public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
}
View Code

 

這樣一些介紹方式可能會讓人產生一頭霧水的感覺,或許直觀地看代碼或調試示例源代碼程序可能會更容易理解一些。下面就把源碼貼上來弓大家參考,希望能對大家有所幫助!

下載源碼

 

 

本文引自:https://www.cnblogs.com/uu102/archive/2013/02/16/2913410.html?ivk_sa=1024320u


免責聲明!

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



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