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.

110 lines
2.9 KiB

4 years ago
4 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 int _port = 80;
  14. private string _ip = "127.0.0.1";
  15. /// <summary></summary>
  16. public Action<HttpListenerContext> Action { get; set; }
  17. /// <summary></summary>
  18. public string IP
  19. {
  20. get { return _ip; }
  21. set { _ip = NetworkUtility.IsIP(value) ? value : "127.0.0.1"; }
  22. }
  23. /// <summary></summary>
  24. public int Port
  25. {
  26. get { return _port; }
  27. set { _port = Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, value)); }
  28. }
  29. /// <summary></summary>
  30. public Exception Start()
  31. {
  32. var prefix = $"http://{_ip}:{Port}/";
  33. Logger.Web.Info(this, $"准备在 {prefix} 启动。");
  34. _listener = new System.Net.HttpListener();
  35. try
  36. {
  37. _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  38. _listener.Prefixes.Add(prefix);
  39. _listener.Start();
  40. // 多线程方式处理请求。
  41. // _thread = new Thread(Listen);
  42. // _thread.IsBackground = true;
  43. // _thread.Start();
  44. // 异步方式处理请求。
  45. _listener.BeginGetContext(Received, null);
  46. Logger.Web.Info(this, $"已在 {prefix} 启动。");
  47. return null;
  48. }
  49. catch (Exception ex)
  50. {
  51. Logger.Web.Exception(this, ex);
  52. Logger.Web.Info(this, $"在 {prefix} 启动失败。");
  53. return ex;
  54. }
  55. }
  56. /// <summary></summary>
  57. public void Stop()
  58. {
  59. if (_thread != null)
  60. {
  61. // _thread.Abort();
  62. _thread = null;
  63. }
  64. if (_listener != null)
  65. {
  66. _listener.Close();
  67. _listener.Stop();
  68. _listener = null;
  69. }
  70. }
  71. void Received(IAsyncResult ar)
  72. {
  73. _listener.BeginGetContext(Received, null);
  74. var context = _listener.EndGetContext(ar);
  75. var action = Action;
  76. if (action != null) action(context);
  77. }
  78. void Listen()
  79. {
  80. while (true)
  81. {
  82. if (_listener == null) break;
  83. var context = _listener.GetContext();
  84. var action = Action;
  85. if (action == null) continue;
  86. action(context);
  87. // RuntimeUtility.InBackground(() => action(context), true);
  88. }
  89. }
  90. }
  91. }