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.

88 lines
2.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Net;
  6. namespace Apewer.Network
  7. {
  8. /// <summary></summary>
  9. public class HttpServer
  10. {
  11. private HttpListener _listener;
  12. private Thread _thread;
  13. private int _port = 80;
  14. /// <summary></summary>
  15. public Action<HttpListenerContext> Action { get; set; }
  16. /// <summary></summary>
  17. public int Port
  18. {
  19. get { return _port; }
  20. set { _port = Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, value)); }
  21. }
  22. /// <summary></summary>
  23. public Exception Start(int port)
  24. {
  25. _listener = new HttpListener();
  26. try
  27. {
  28. _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  29. _listener.Prefixes.Add("http://0.0.0.0:" + port.ToString() + "/");
  30. _listener.Start();
  31. _thread = new Thread(Listen);
  32. _thread.IsBackground = true;
  33. _thread.Start();
  34. return null;
  35. }
  36. catch (Exception e)
  37. {
  38. return e;
  39. }
  40. }
  41. /// <summary></summary>
  42. public void Stop()
  43. {
  44. if (_thread != null)
  45. {
  46. _thread.Abort();
  47. _thread = null;
  48. }
  49. if (_listener != null)
  50. {
  51. _listener.Close();
  52. _listener.Stop();
  53. _listener = null;
  54. }
  55. }
  56. private void Listen()
  57. {
  58. while (true)
  59. {
  60. if (_listener == null) break;
  61. var context = _listener.GetContext();
  62. var thread = new Thread((obj) =>
  63. {
  64. try { Action?.Invoke(context); }
  65. catch (Exception e) { var __e = e; }
  66. })
  67. {
  68. IsBackground = true
  69. };
  70. thread.Start(context);
  71. }
  72. }
  73. }
  74. }