LJHttpServer.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Threading;
  10. namespace LJLib.HttpServer
  11. {
  12. public abstract class LJHttpServer
  13. {
  14. private readonly int _port;
  15. TcpListener _listener;
  16. bool is_active = true;
  17. protected LJHttpServer(int port)
  18. {
  19. _port = port;
  20. }
  21. public void Listen()
  22. {
  23. _listener = new TcpListener(IPAddress.Any, _port);
  24. _listener.Start();
  25. ThreadPool.QueueUserWorkItem(state =>
  26. {
  27. // 侦听线程
  28. Thread.CurrentThread.IsBackground = false;
  29. try
  30. {
  31. while (is_active)
  32. {
  33. if (_listener.Pending())
  34. {
  35. TcpClient s = _listener.AcceptTcpClient();
  36. ThreadPool.QueueUserWorkItem(st =>
  37. {
  38. try
  39. {
  40. Thread.CurrentThread.IsBackground = true;
  41. LJHttpProcessor processor = new LJHttpProcessor(s, this);
  42. processor.Process();
  43. }
  44. catch (System.Exception e)
  45. {
  46. Trace.Write("HTTP请求处理线程异常退出:" + e.ToString());
  47. }
  48. });
  49. }
  50. else
  51. {
  52. Thread.Sleep(100);
  53. }
  54. }
  55. }
  56. catch (System.Exception e)
  57. {
  58. Trace.Write("HTTP监听异常退出:" + e.ToString());
  59. }
  60. });
  61. }
  62. public void Stop()
  63. {
  64. is_active = false;
  65. }
  66. public abstract void HandleGetRequest(LJHttpProcessor p);
  67. public abstract void HandlePostRequest(LJHttpProcessor p, StreamReader inputData);
  68. }
  69. }