本文以兩種稍微有差別的方式用C#語言實(shí)現(xiàn)HTTP協(xié)議的服務(wù)器類,之所以寫這些,也是為了自己能更深刻了解HTTP底層運(yùn)作。
要完成高性能的Web服務(wù)功能,通常都是需要寫入到服務(wù),如IIS,Apache Tomcat,但是眾所周知的Web服務(wù)器配置的復(fù)雜性,如果我們只是需要一些簡單的功能,安裝這些組件看起來就沒多大必要。我們需要的是一個(gè)簡單的HTTP類,可以很容易地嵌入到簡單的Web請求的服務(wù),加到自己的程序里。
實(shí)現(xiàn)方法一:
.net框架下有一個(gè)簡單但很強(qiáng)大的類HttpListener。這個(gè)類幾行代碼就能完成一個(gè)簡單的服務(wù)器功能。雖然以下內(nèi)容在實(shí)際運(yùn)行中幾乎毫無價(jià)值,但是也不失為理解HTTP請求過程的細(xì)節(jié)原理的好途徑。
復(fù)制代碼代碼如下:
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>測試服務(wù)器</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();
如果你運(yùn)用的好,舉一反三的話,這樣一個(gè)簡單的類可能會(huì)收到意想不到的效果,但是由于HttpListener這個(gè)類對底層的完美封裝,導(dǎo)致對協(xié)議的控制失去靈活性,因此我想大型服務(wù)器程序里肯定不會(huì)用這個(gè)類去實(shí)現(xiàn)。因此如果必要的話,自己用Tcp協(xié)議再去封裝一個(gè)類,以便更好的控制服務(wù)運(yùn)行狀態(tài)。
實(shí)現(xiàn)方法二:
這個(gè)方法是一個(gè)老外分享的,雖然文件內(nèi)容看起來很亂,其實(shí)邏輯很強(qiáng)很有條理。讓我們來分析一下實(shí)現(xiàn)過程:
通過子類化HttpServer和兩個(gè)抽象方法handlegetrequest和handlepostrequest提供實(shí)現(xiàn)…
復(fù)制代碼代碼如下:
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);
}
}
如果你能夠順利編譯和運(yùn)行附件中的項(xiàng)目,就你應(yīng)該能夠用Web瀏覽器輸入Http://localhost:8080/,打開就可以看上面的簡單的HTML頁面渲染。讓我們看看怎么具體是怎么實(shí)現(xiàn)的吧~!
這個(gè)簡單的Web服務(wù)器可以分解為兩個(gè)部分。HttpServer類開啟了一個(gè)指定輸入端口的TcpListener實(shí)例,使用accepttcpclient()用于循環(huán)處理傳入的TCP連接請求。這是處理傳入的TCP連接的第一步。當(dāng)傳入的請求到達(dá)已知的指定端口,這個(gè)接受過程會(huì)創(chuàng)建一個(gè)新的服務(wù)器與客戶端端口配對,用于服務(wù)器語言客戶端的連接通信。
復(fù)制代碼代碼如下:
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);
}
這樣一些介紹方式可能會(huì)讓人產(chǎn)生一頭霧水的感覺,或許直觀地看代碼或調(diào)試示例源代碼程序可能會(huì)更容易理解一些。下面就把源碼貼上來弓大家參考,希望能對大家有所幫助!
點(diǎn)擊下載