首页 > 编程 > C# > 正文

C#实现HTTP协议迷你服务器(两种方法)

2020-04-24 21:08:45
字体:
来源:转载
供稿:网友
本文以两种稍微有差别的方式用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>");
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表