https://www.cnblogs.com/tuyile006/p/11857590.html

简介

本文用C#实现了一个最简单的HTTP服务器类,你可以将它嵌入到自己的项目中,或者也可以阅读代码来学习关于HTTP协议的知识。

背景

高性能的WEB应用一般都架设在强大的WEB服务器上,例如IIS, Apache, 和Tomcat。然而,HTML是非常灵活的UI标记语言,也就是说任何应用和后端服务都可以提供HTML的生成支持。在这个小小的例子中,像IIS,、Apache这样的服务器消耗的资源太大了,我们需要自己实现一个简单的HTTP服务器,将它嵌入到我们的应用中用来处理WEB请求。我们仅需要一个类就可以实现了,很简单。

代码实现

首先我们来回顾一下如何使用类,然后我们再来分析实现的具体细节。这里我们创建了一个继承于HttpServer的类,并实现了handleGETRequest 和handlePOSTRequest 这两个抽象方法:

  1. using System;
  2. using System.IO;
  3. public class MyHttpServer : HttpServer
  4. {
  5. public MyHttpServer(int port) : base(port)
  6. {
  7. }
  8. public override void handleGETRequest(HttpProcessor p)
  9. {
  10. Console.WriteLine("request: {0}", p.http_url);
  11. p.writeSuccess();
  12. p.outputStream.WriteLine("<html><body><h1>test server</h1>");
  13. p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
  14. p.outputStream.WriteLine("url : {0}", p.http_url);
  15. p.outputStream.WriteLine("<form method=post action=/form>");
  16. p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
  17. p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
  18. p.outputStream.WriteLine("</form>");
  19. }
  20. public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
  21. {
  22. Console.WriteLine("POST request: {0}", p.http_url);
  23. string data = inputData.ReadToEnd();
  24. p.outputStream.WriteLine("<html><body><h1>test server</h1>");
  25. p.outputStream.WriteLine("<a href=/test>return</a><p>");
  26. p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
  27. }
  28. }

当开始处理一个简单的请求时,我们就需要单独启动一个线程来监听一个端口,比如8080端口:

  1. HttpServer httpServer = new MyHttpServer(8080);
  2. Thread thread = new Thread(newThreadStart(httpServer.listen));
  3. thread.Start();

如果你编译运行这个项目,你会在浏览器http://localhost:8080地址下看到页面上生成的示例内容。让我们来简单看一下这个HTTP服务器引擎是怎么实现的。

这个WEB服务器由两个组件构成,一个是负责启动TcpListener来监听指定端口的HttpServer类,并且用AcceptTcpClient()方法循环处理TCP连接请求,这是处理TCP连接的第一步。然后请求到达“已指定“的端口,接着就会创建一对新的端口,用来初始化客户端到服务器端的TCP连接。这对端口便是TcpClient的session,这样就可以保持我们的主端口可以继续接收新的连接请求。从下面的代码中我们可以看到,每一次监听程序都会创建一个新的TcpClien,HttpServer类又会创建一个新的HttpProcessor,然后启动一个线程来操作。HttpServer类中还包含两个抽象方法,你必须实现这两个方法。

  1. using System.IO;
  2. using System.Net.Sockets;
  3. using System.Threading;
  4. public abstract class HttpServer
  5. {
  6. protected int port;
  7. TcpListener listener;
  8. bool is_active = true;
  9. public HttpServer(int port)
  10. {
  11. this.port = port;
  12. }
  13. public void listen()
  14. {
  15. listener = new TcpListener(port);
  16. listener.Start();
  17. while (is_active)
  18. {
  19. TcpClient s = listener.AcceptTcpClient();
  20. HttpProcessor processor = new HttpProcessor(s, this);
  21. Thread thread = new Thread(new ThreadStart(processor.process));
  22. thread.Start();
  23. Thread.Sleep(1);
  24. }
  25. }
  26. public abstract void handleGETRequest(HttpProcessor p);
  27. public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
  28. }

这样,一个新的tcp连接就在自己的线程中被HttpProcessor处理了,HttpProcessor的工作就是正确解析HTTP头,并且控制正确实现的抽象方法。下面我们来看看HTTP头的处理过程,HTTP请求的第一行代码如下:

  1. GET /myurl HTTP/1.0

在设置完process()的输入和输出后,HttpProcessor就会调用parseRequest()方法。

  1. public void parseRequest()
  2. {
  3. String request = streamReadLine(inputStream);
  4. string[] tokens = request.Split(' ');
  5. if (tokens.Length != 3)
  6. {
  7. throw new Exception("invalid http request line");
  8. }
  9. http_method = tokens[0].ToUpper();
  10. http_url = tokens[1];
  11. http_protocol_versionstring = tokens[2];
  12. Console.WriteLine("starting: " + request);
  13. }

HTTP请求由3部分组成,所以我们只需要用string.Split()方法将它们分割成3部分即可,接下来就是接收和解析来自客户端的HTTP头信息,头信息中的每一行数据是以Key-Value(键-值)形式保存,空行表示HTTP头信息结束标志,我们代码中用readHeaders方法来读取HTTP头信息:

  1. public void readHeaders()
  2. {
  3. Console.WriteLine("readHeaders()");
  4. String line;
  5. while ((line = streamReadLine(inputStream)) != null)
  6. {
  7. if (line.Equals(""))
  8. {
  9. Console.WriteLine("got headers");
  10. return;
  11. }
  12. int separator = line.IndexOf(':');
  13. if (separator == -1)
  14. {
  15. throw new Exception("invalid http header line: " + line);
  16. }
  17. String name = line.Substring(0, separator);
  18. int pos = separator + 1;
  19. while ((pos < line.Length) && (line[pos] == ' '))
  20. {
  21. pos++; // strip any spaces
  22. }
  23. string value = line.Substring(pos, line.Length - pos);
  24. Console.WriteLine("header: {0}:{1}", name, value);
  25. httpHeaders[name] = value;
  26. }
  27. }

到这里,我们已经了解了如何处理简单的GET和POST请求,它们分别被分配给正确的handler处理程序。在本例中,发送数据的时候有一个棘手的问题需要处理,那就是请求头信息中包含发送数据的长度信息content-length,当我们希望子类HttpServer中的handlePOSTRequest方法能够正确处理数据时,我们需要将数据长度content-length信息一起放入数据流中,否则发送端会因为等待永远不可能到达的数据和阻塞等待。我们用了一种看起来不那么优雅但非常有效的方法来处理这种情况,即将数据发送给POST处理方法前先把数据读入到MemoryStream中。这种做法不太理想,原因如下:如果发送的数据很大,甚至是上传一个文件,那么我们将这些数据缓存在内存就不那么合适甚至是不可能的。理想的方法是限制post的长度,比如我们可以将数据长度限制为10MB。

这个简易版HTTP服务器另一个简化的地方就是content-type的返回值,在HTTP协议中,服务器总是会将数据的MIME-Type发送给客户端,告诉客户端自己需要接收什么类型的数据。在writeSuccess()方法中,我们看到,服务器总是发送text/html类型,如果你需要加入其他的类型,你可以扩展这个方法。

完整代码

HttpServer

  1. using System.IO;
  2. using System.Net.Sockets;
  3. using System.Threading;
  4. public abstract class HttpServer
  5. {
  6. protected int port;
  7. TcpListener listener;
  8. bool is_active = true;
  9. public HttpServer(int port)
  10. {
  11. this.port = port;
  12. }
  13. public void listen()
  14. {
  15. listener = new TcpListener(port);
  16. listener.Start();
  17. while (is_active)
  18. {
  19. TcpClient s = listener.AcceptTcpClient();
  20. HttpProcessor processor = new HttpProcessor(s, this);
  21. Thread thread = new Thread(new ThreadStart(processor.process));
  22. thread.Start();
  23. Thread.Sleep(1);
  24. }
  25. }
  26. public abstract void handleGETRequest(HttpProcessor p);
  27. public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
  28. }

MyHttpServer

  1. using System;
  2. using System.IO;
  3. public class MyHttpServer : HttpServer
  4. {
  5. public MyHttpServer(int port) : base(port)
  6. {
  7. }
  8. public override void handleGETRequest(HttpProcessor p)
  9. {
  10. Console.WriteLine("request: {0}", p.http_url);
  11. p.writeSuccess();
  12. p.outputStream.WriteLine("<html><body><h1>test server</h1>");
  13. p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
  14. p.outputStream.WriteLine("url : {0}", p.http_url);
  15. p.outputStream.WriteLine("<form method=post action=/form>");
  16. p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
  17. p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
  18. p.outputStream.WriteLine("</form>");
  19. }
  20. public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
  21. {
  22. Console.WriteLine("POST request: {0}", p.http_url);
  23. string data = inputData.ReadToEnd();
  24. p.outputStream.WriteLine("<html><body><h1>test server</h1>");
  25. p.outputStream.WriteLine("<a href=/test>return</a><p>");
  26. p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
  27. }
  28. }

HttpProcessor

  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. public class HttpProcessor
  7. {
  8. public TcpClient socket;
  9. public HttpServer srv;
  10. private Stream inputStream;
  11. public StreamWriter outputStream;
  12. public String http_method;
  13. public String http_url;
  14. public String http_protocol_versionstring;
  15. public Hashtable httpHeaders = new Hashtable();
  16. private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB
  17. public HttpProcessor(TcpClient s, HttpServer srv)
  18. {
  19. this.socket = s;
  20. this.srv = srv;
  21. }
  22. private string streamReadLine(Stream inputStream)
  23. {
  24. int next_char;
  25. string data = "";
  26. while (true)
  27. {
  28. next_char = inputStream.ReadByte();
  29. if (next_char == '\n')
  30. {
  31. break;
  32. }
  33. if (next_char == '\r')
  34. {
  35. continue;
  36. }
  37. if (next_char == -1)
  38. {
  39. Thread.Sleep(1);
  40. continue;
  41. }
  42. ;
  43. data += Convert.ToChar(next_char);
  44. }
  45. return data;
  46. }
  47. public void process()
  48. {
  49. // we can't use a StreamReader for input, because it buffers up extra data on us inside it's
  50. // "processed" view of the world, and we want the data raw after the headers
  51. inputStream = new BufferedStream(socket.GetStream());
  52. // we probably shouldn't be using a streamwriter for all output from handlers either
  53. outputStream = new StreamWriter(new BufferedStream(socket.GetStream()));
  54. try
  55. {
  56. parseRequest();
  57. readHeaders();
  58. if (http_method.Equals("GET"))
  59. {
  60. handleGETRequest();
  61. }
  62. else if (http_method.Equals("POST"))
  63. {
  64. handlePOSTRequest();
  65. }
  66. }
  67. catch (Exception e)
  68. {
  69. Console.WriteLine("Exception: " + e.ToString());
  70. writeFailure();
  71. }
  72. outputStream.Flush();
  73. // bs.Flush(); // flush any remaining output
  74. inputStream = null;
  75. outputStream = null; // bs = null;
  76. socket.Close();
  77. }
  78. public void parseRequest()
  79. {
  80. String request = streamReadLine(inputStream);
  81. string[] tokens = request.Split(' ');
  82. if (tokens.Length != 3)
  83. {
  84. throw new Exception("invalid http request line");
  85. }
  86. http_method = tokens[0].ToUpper();
  87. http_url = tokens[1];
  88. http_protocol_versionstring = tokens[2];
  89. Console.WriteLine("starting: " + request);
  90. }
  91. public void readHeaders()
  92. {
  93. Console.WriteLine("readHeaders()");
  94. String line;
  95. while ((line = streamReadLine(inputStream)) != null)
  96. {
  97. if (line.Equals(""))
  98. {
  99. Console.WriteLine("got headers");
  100. return;
  101. }
  102. int separator = line.IndexOf(':');
  103. if (separator == -1)
  104. {
  105. throw new Exception("invalid http header line: " + line);
  106. }
  107. String name = line.Substring(0, separator);
  108. int pos = separator + 1;
  109. while ((pos < line.Length) && (line[pos] == ' '))
  110. {
  111. pos++; // strip any spaces
  112. }
  113. string value = line.Substring(pos, line.Length - pos);
  114. Console.WriteLine("header: {0}:{1}", name, value);
  115. httpHeaders[name] = value;
  116. }
  117. }
  118. public void handleGETRequest()
  119. {
  120. srv.handleGETRequest(this);
  121. }
  122. private const int BUF_SIZE = 4096;
  123. public void handlePOSTRequest()
  124. {
  125. // this post data processing just reads everything into a memory stream.
  126. // this is fine for smallish things, but for large stuff we should really
  127. // hand an input stream to the request processor. However, the input stream
  128. // we hand him needs to let him see the "end of the stream" at this content
  129. // length, because otherwise he won't know when he's seen it all!
  130. Console.WriteLine("get post data start");
  131. int content_len = 0;
  132. MemoryStream ms = new MemoryStream();
  133. if (this.httpHeaders.ContainsKey("Content-Length"))
  134. {
  135. content_len = Convert.ToInt32(this.httpHeaders["Content-Length"]);
  136. if (content_len > MAX_POST_SIZE)
  137. {
  138. throw new Exception(
  139. String.Format("POST Content-Length({0}) too big for this simple server",
  140. content_len));
  141. }
  142. byte[] buf = new byte[BUF_SIZE];
  143. int to_read = content_len;
  144. while (to_read > 0)
  145. {
  146. Console.WriteLine("starting Read, to_read={0}", to_read);
  147. int numread = this.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
  148. Console.WriteLine("read finished, numread={0}", numread);
  149. if (numread == 0)
  150. {
  151. if (to_read == 0)
  152. {
  153. break;
  154. }
  155. else
  156. {
  157. throw new Exception("client disconnected during post");
  158. }
  159. }
  160. to_read -= numread;
  161. ms.Write(buf, 0, numread);
  162. }
  163. ms.Seek(0, SeekOrigin.Begin);
  164. }
  165. Console.WriteLine("get post data end");
  166. srv.handlePOSTRequest(this, new StreamReader(ms));
  167. }
  168. public void writeSuccess()
  169. {
  170. outputStream.WriteLine("HTTP/1.0 200 OK");
  171. outputStream.WriteLine("Content-Type: text/html;charset=utf-8");
  172. outputStream.WriteLine("Connection: close");
  173. outputStream.WriteLine("");
  174. }
  175. public void writeFailure()
  176. {
  177. outputStream.WriteLine("HTTP/1.0 404 File not found");
  178. outputStream.WriteLine("Connection: close");
  179. outputStream.WriteLine("");
  180. }
  181. }

TestMain

  1. using System.Threading;
  2. public class TestMain
  3. {
  4. public static int Main(String[] args)
  5. {
  6. HttpServer httpServer;
  7. if (args.GetLength(0) > 0)
  8. {
  9. httpServer = new MyHttpServer(Convert.ToInt16(args[0]));
  10. }
  11. else
  12. {
  13. httpServer = new MyHttpServer(8080);
  14. }
  15. Thread thread = new Thread(new ThreadStart(httpServer.listen));
  16. thread.Start();
  17. return 0;
  18. }
  19. }