请选择 进入手机版 | 继续访问电脑版
查看: 552|回复: 0

[ASP.NET教程] C# 实现一个简单的 HTTP 服务器

3万

主题

3万

帖子

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
100197
发表于 2015-11-23 18:11:16
<无详细内容>
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Threading;
  6. class MainClass {
  7. private static int maxRequestHandlers = 5;
  8. private static int requestHandlerID = 0;
  9. private static HttpListener listener;
  10. private static void RequestHandler(IAsyncResult result) {
  11. try {
  12. HttpListenerContext context = listener.EndGetContext(result);
  13. StreamWriter sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8);
  14. sw.WriteLine("<html><head><title>C# </title>");
  15. sw.WriteLine("</head><body>" + result.AsyncState);
  16. sw.WriteLine("</body></html>");
  17. sw.Flush();
  18. context.Response.ContentType = "text/html";
  19. context.Response.ContentEncoding = Encoding.UTF8;
  20. context.Response.Close();
  21. } catch (ObjectDisposedException) {
  22. Console.WriteLine(result.AsyncState);
  23. } finally {
  24. if (listener.IsListening) {
  25. listener.BeginGetContext(RequestHandler,
  26. "RequestHandler_" + Interlocked.Increment(ref requestHandlerID));
  27. }
  28. }
  29. }
  30. public static void Main(string[] args) {
  31. using (listener = new HttpListener()) {
  32. listener.Prefixes.Add("http://localhost:8080/");
  33. listener.Start();
  34. for (int count = 0; count < maxRequestHandlers; count++) {
  35. listener.BeginGetContext(RequestHandler, "RequestHandler_" +
  36. Interlocked.Increment(ref requestHandlerID));
  37. }
  38. Console.WriteLine("Press Enter to stop the HTTP Server");
  39. Console.ReadLine();
  40. listener.Stop();
  41. listener.Abort();
  42. }
  43. }
  44. }
复制代码


回复

使用道具 举报