1
0

AsyncHttpClient.cpp 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #include "AsyncHttpClient.h"
  2. namespace hv {
  3. int AsyncHttpClient::sendInLoopImpl(const HttpRequestPtr& req, HttpResponseCallback resp_cb, uint64_t start_hrtime) {
  4. // queueInLoop timeout?
  5. uint64_t now_hrtime = hloop_now_hrtime(loop_thread.hloop());
  6. int elapsed_ms = (now_hrtime - start_hrtime) / 1000;
  7. int timeout_ms = req->timeout * 1000;
  8. if (timeout_ms > 0 && elapsed_ms >= timeout_ms) {
  9. hlogw("%s queueInLoop timeout!", req->url.c_str());
  10. return -10;
  11. }
  12. req->ParseUrl();
  13. sockaddr_u peeraddr;
  14. memset(&peeraddr, 0, sizeof(peeraddr));
  15. int ret = sockaddr_set_ipport(&peeraddr, req->host.c_str(), req->port);
  16. if (ret != 0) {
  17. hloge("unknown host %s", req->host.c_str());
  18. return -20;
  19. }
  20. int connfd = -1;
  21. hio_t* connio = NULL;
  22. HttpClientContextPtr ctx = NULL;
  23. // first get from conn_pools
  24. char strAddr[SOCKADDR_STRLEN] = {0};
  25. SOCKADDR_STR(&peeraddr, strAddr);
  26. auto iter = conn_pools.find(strAddr);
  27. if (iter != conn_pools.end()) {
  28. if (iter->second.get(connfd)) {
  29. // hlogd("get from conn_pools");
  30. ctx = getContext(connfd);
  31. ctx->req = req;
  32. ctx->cb = resp_cb;
  33. }
  34. }
  35. if (connfd < 0) {
  36. // create socket
  37. connfd = socket(peeraddr.sa.sa_family, SOCK_STREAM, 0);
  38. if (connfd < 0) {
  39. perror("socket");
  40. return -30;
  41. }
  42. connio = hio_get(loop_thread.hloop(), connfd);
  43. assert(connio != NULL);
  44. hio_set_peeraddr(connio, &peeraddr.sa, sockaddr_len(&peeraddr));
  45. // https
  46. if (req->https) {
  47. hio_enable_ssl(connio);
  48. }
  49. }
  50. if (ctx == NULL) {
  51. // new HttpClientContext
  52. ctx.reset(new HttpClientContext);
  53. ctx->req = req;
  54. ctx->cb = resp_cb;
  55. ctx->channel.reset(new SocketChannel(connio));
  56. ctx->channel->onread = [this, ctx](Buffer* buf) {
  57. const char* data = (const char*)buf->data();
  58. int len = buf->size();
  59. int nparse = ctx->parser->FeedRecvData(data, len);
  60. if (nparse != len) {
  61. ctx->errorCallback();
  62. ctx->channel->close();
  63. return;
  64. }
  65. if (ctx->parser->IsComplete()) {
  66. std::string req_connection = ctx->req->GetHeader("Connection");
  67. std::string resp_connection = ctx->resp->GetHeader("Connection");
  68. ctx->successCallback();
  69. if (stricmp(req_connection.c_str(), "keep-alive") == 0 &&
  70. stricmp(resp_connection.c_str(), "keep-alive") == 0) {
  71. // add into conn_pools to reuse
  72. // hlogd("add into conn_pools");
  73. conn_pools[ctx->channel->peeraddr()].add(ctx->channel->fd());
  74. } else {
  75. ctx->channel->close();
  76. }
  77. }
  78. };
  79. ctx->channel->onclose = [this, ctx]() {
  80. ctx->channel->status = SocketChannel::CLOSED;
  81. removeContext(ctx);
  82. ctx->errorCallback();
  83. };
  84. addContext(ctx);
  85. }
  86. // timer
  87. if (timeout_ms > 0) {
  88. ctx->timerID = setTimeout(timeout_ms - elapsed_ms, [ctx](TimerID timerID){
  89. hlogw("%s timeout!", ctx->req->url.c_str());
  90. if (ctx->channel) {
  91. ctx->channel->close();
  92. }
  93. });
  94. }
  95. if (ctx->channel->isConnected()) {
  96. // sendRequest
  97. sendRequest(ctx);
  98. } else {
  99. // startConnect
  100. hevent_set_userdata(connio, this);
  101. hio_setcb_connect(connio, onconnect);
  102. hio_connect(connio);
  103. }
  104. return 0;
  105. }
  106. void AsyncHttpClient::onconnect(hio_t* io) {
  107. AsyncHttpClient* client = (AsyncHttpClient*)hevent_userdata(io);
  108. HttpClientContextPtr ctx = client->getContext(hio_fd(io));
  109. assert(ctx != NULL && ctx->req != NULL && ctx->channel != NULL);
  110. ctx->channel->status = SocketChannel::CONNECTED;
  111. client->sendRequest(ctx);
  112. ctx->channel->startRead();
  113. }
  114. int AsyncHttpClient::sendRequest(const HttpClientContextPtr ctx) {
  115. assert(ctx != NULL && ctx->req != NULL && ctx->channel != NULL);
  116. SocketChannelPtr channel = ctx->channel;
  117. if (ctx->parser == NULL) {
  118. ctx->parser.reset(HttpParser::New(HTTP_CLIENT, (http_version)ctx->req->http_major));
  119. }
  120. if (ctx->resp == NULL) {
  121. ctx->resp.reset(new HttpResponse);
  122. }
  123. ctx->parser->InitResponse(ctx->resp.get());
  124. ctx->parser->SubmitRequest(ctx->req.get());
  125. char* data = NULL;
  126. size_t len = 0;
  127. while (ctx->parser->GetSendData(&data, &len)) {
  128. Buffer buf(data, len);
  129. channel->write(&buf);
  130. }
  131. return 0;
  132. }
  133. }