You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.6 KiB

4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Net;
  6. namespace Apewer.Web
  7. {
  8. /// <summary></summary>
  9. public class HttpListener
  10. {
  11. private System.Net.HttpListener _listener;
  12. private Thread _thread;
  13. private string _prefix = "http://*:0/";
  14. /// <summary></summary>
  15. public Action<HttpListenerContext> Action { get; set; }
  16. /// <summary></summary>
  17. public string Prefix
  18. {
  19. get { return _prefix; }
  20. set { _prefix = value ?? ""; }
  21. }
  22. /// <summary></summary>
  23. public Exception Start()
  24. {
  25. var prefix = Prefix;
  26. Logger.Web.Info(this, $"准备在 {Prefix} 启动。");
  27. _listener = new System.Net.HttpListener();
  28. try
  29. {
  30. _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  31. _listener.Prefixes.Add(prefix);
  32. _listener.Start();
  33. // 多线程方式处理请求。
  34. // _thread = new Thread(Listen);
  35. // _thread.IsBackground = true;
  36. // _thread.Start();
  37. // 异步方式处理请求。
  38. _listener.BeginGetContext(Received, null);
  39. Logger.Web.Info(this, $"已在 {prefix} 启动。");
  40. return null;
  41. }
  42. catch (Exception ex)
  43. {
  44. Logger.Web.Exception(ex, this);
  45. Logger.Web.Info(this, $"在 {prefix} 启动失败。");
  46. return ex;
  47. }
  48. }
  49. /// <summary></summary>
  50. public void Stop()
  51. {
  52. if (_thread != null)
  53. {
  54. // _thread.Abort();
  55. _thread = null;
  56. }
  57. if (_listener != null)
  58. {
  59. _listener.Close();
  60. _listener.Stop();
  61. _listener = null;
  62. }
  63. }
  64. void Received(IAsyncResult ar)
  65. {
  66. _listener.BeginGetContext(Received, null);
  67. var context = _listener.EndGetContext(ar);
  68. var action = Action;
  69. if (action != null) action(context);
  70. }
  71. void Listen()
  72. {
  73. while (true)
  74. {
  75. if (_listener == null) break;
  76. var context = _listener.GetContext();
  77. var action = Action;
  78. if (action == null) continue;
  79. action(context);
  80. // RuntimeUtility.InBackground(() => action(context), true);
  81. }
  82. }
  83. }
  84. }