C#實(shí)現(xiàn)HTTP協(xié)議迷你服務(wù)器(兩種方法)
2024-09-07 17:05:35
供稿:網(wǎng)友
本文以兩種稍微有差別的方式用C#語(yǔ)言實(shí)現(xiàn)HTTP協(xié)議的服務(wù)器類(lèi),之所以寫(xiě)這些,也是為了自己能更深刻了解HTTP底層運(yùn)作。
要完成高性能的Web服務(wù)功能,通常都是需要寫(xiě)入到服務(wù),如IIS,Apache Tomcat,但是眾所周知的Web服務(wù)器配置的復(fù)雜性,如果我們只是需要一些簡(jiǎn)單的功能,安裝這些組件看起來(lái)就沒(méi)多大必要。我們需要的是一個(gè)簡(jiǎn)單的HTTP類(lèi),可以很容易地嵌入到簡(jiǎn)單的Web請(qǐng)求的服務(wù),加到自己的程序里。
實(shí)現(xiàn)方法一:
.net框架下有一個(gè)簡(jiǎn)單但很強(qiáng)大的類(lèi)HttpListener。這個(gè)類(lèi)幾行代碼就能完成一個(gè)簡(jiǎn)單的服務(wù)器功能。雖然以下內(nèi)容在實(shí)際運(yùn)行中幾乎毫無(wú)價(jià)值,但是也不失為理解HTTP請(qǐng)求過(guò)程的細(xì)節(jié)原理的好途徑。
代碼如下:
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>測(cè)試服務(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è)簡(jiǎn)單的類(lèi)可能會(huì)收到意想不到的效果,但是由于HttpListener這個(gè)類(lèi)對(duì)底層的完美封裝,導(dǎo)致對(duì)協(xié)議的控制失去靈活性,因此我想大型服務(wù)器程序里肯定不會(huì)用這個(gè)類(lèi)去實(shí)現(xiàn)。因此如果必要的話,自己用Tcp協(xié)議再去封裝一個(gè)類(lèi),以便更好的控制服務(wù)運(yùn)行狀態(tài)。
實(shí)現(xiàn)方法二:
這個(gè)方法是一個(gè)老外分享的,雖然文件內(nèi)容看起來(lái)很亂,其實(shí)邏輯很強(qiáng)很有條理。讓我們來(lái)分析一下實(shí)現(xiàn)過(guò)程:
通過(guò)子類(lèi)化HttpServer和兩個(gè)抽象方法handlegetrequest和handlepostrequest提供實(shí)現(xiàn)…
代碼如下:
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>");