HttpServer.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System.IO;
  2. using IFramework.Net.Tcp;
  3. namespace IFramework.Net.Http
  4. {
  5. public delegate void HttpOnReceived(HttpPayload payload);
  6. internal class HttpServer : IHttpServerProvider
  7. {
  8. private ITcpServerProvider sProvider = null;
  9. public HttpOnReceived hOnReceived { get; set; }
  10. public int Port { get; private set; }
  11. public HttpServer(int maxPoolCount = 64, int blockSize = 4096)
  12. {
  13. sProvider = NetTool.CreateTcpSever(blockSize, maxPoolCount);
  14. sProvider.DisconnectedCallback = new OnDisconnectedHandler(OnDisconnected);
  15. sProvider.ReceivedOffsetCallback = new OnReceivedSegmentHandler(OnReceived);
  16. sProvider.AcceptedCallback = new OnAcceptedHandler(OnAccepted);
  17. }
  18. public bool Start(int port = 80)
  19. {
  20. this.Port = port;
  21. bool isOk = sProvider.Start(port);
  22. return isOk;
  23. }
  24. public bool Send(SocketToken sToken,byte[] data)
  25. {
  26. return sProvider.Send(new SegmentToken(sToken, data));
  27. }
  28. public bool Send(SegmentToken segment)
  29. {
  30. return sProvider.Send(segment);
  31. }
  32. public void Disconnect(SocketToken sToken)
  33. {
  34. sProvider.Close(sToken);
  35. }
  36. private void OnReceived(SegmentToken sToken)
  37. {
  38. if (hOnReceived != null)
  39. {
  40. HttpHeader header = new HttpHeader(sToken.Data);
  41. switch (header.Option)
  42. {
  43. case HttpOption.GET:
  44. hOnReceived(new HttpGet(header).GetDo(sToken));
  45. break;
  46. case HttpOption.POST:
  47. hOnReceived(new HttpPost(header).GetDo(sToken));
  48. break;
  49. }
  50. }
  51. }
  52. private void OnAccepted(SocketToken sToken)
  53. {
  54. }
  55. private void OnDisconnected(SocketToken sToken)
  56. {
  57. }
  58. }
  59. public class HttpPayload
  60. {
  61. public SocketToken Token { get; set; }
  62. public HttpHeader Header { get; set; }
  63. public HttpUri HttpUri { get; set; }
  64. public Stream stream { get; set; }
  65. }
  66. }