程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> C#實現HTTP協議迷你服務器(兩種方法)

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

編輯:ASP.NET基礎
本文以兩種稍微有差別的方式用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;
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);
}

這樣一些介紹方式可能會讓人產生一頭霧水的感覺,或許直觀地看代碼或調試示例源代碼程序可能會更容易理解一些。下面就把源碼貼上來弓大家參考,希望能對大家有所幫助!
點擊下載
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved