ClientConnection.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //
  2. // Created by xcbosa on 2023/1/28.
  3. //
  4. #include "ClientConnection.h"
  5. using namespace std;
  6. namespace xc {
  7. namespace httpserver {
  8. ClientConnection::ClientConnection(int sockFd, struct sockaddr_in address) {
  9. this->sockFd = sockFd;
  10. this->address = address;
  11. this->clRead = nullptr;
  12. this->clWrite = nullptr;
  13. this->requestBuff = nullptr;
  14. }
  15. void ClientConnection::workAndDestroy() {
  16. thread(&ClientConnection::workLoop, this).detach();
  17. }
  18. void ClientConnection::workLoop() {
  19. ::FILE *clRead = fdopen(this->sockFd, "r");
  20. ::FILE *clWrite = fdopen(dup(this->sockFd), "w");
  21. this->clRead = clRead;
  22. this->clWrite = clWrite;
  23. char *requestBuff = (char *)::malloc(urlRequestBuffSize);
  24. this->requestBuff = requestBuff;
  25. ::fgets(requestBuff, urlRequestBuffSize, clRead);
  26. if (::strstr(requestBuff, "HTTP/") == NULL) {
  27. conf::errorPage400.writeTo(clWrite);
  28. cleanUpAndDestroy();
  29. return;
  30. }
  31. string method, url;
  32. char *ptr, *p;
  33. ptr = strtok_r(requestBuff, " ", &p);
  34. if (ptr != nullptr) {
  35. method = string(ptr);
  36. ptr = strtok_r(NULL, " ", &p);
  37. if (ptr != nullptr) {
  38. url = string(ptr);
  39. }
  40. }
  41. if (method == "GET1") {
  42. } else if (method == "POST1") {
  43. } else {
  44. conf::errorPage.applyReplacements(400, {
  45. Replacement("errorCode", "400"),
  46. Replacement("errorMessage", "未知的协议 " + method)
  47. }).writeTo(clWrite);
  48. cleanUpAndDestroy();
  49. return;
  50. }
  51. ResponseData(200, string(requestBuff)).writeTo(clWrite);
  52. cleanUpAndDestroy();
  53. return;
  54. }
  55. void ClientConnection::cleanUpAndDestroy() {
  56. if (this->clRead) {
  57. ::fclose(this->clRead);
  58. this->clRead = nullptr;
  59. }
  60. if (this->clWrite) {
  61. ::fclose(this->clWrite);
  62. this->clWrite = nullptr;
  63. }
  64. if (this->requestBuff) {
  65. ::free(this->requestBuff);
  66. this->requestBuff = nullptr;
  67. }
  68. ::close(this->sockFd);
  69. delete this;
  70. }
  71. } // xc
  72. } // httpserver