HttpClient-winrt.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /****************************************************************************
  2. Copyright (c) 2012 greathqy
  3. Copyright (c) 2012 cocos2d-x.org
  4. Copyright (c) 2013-2016 Chukong Technologies Inc.
  5. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "platform/CCPlatformConfig.h"
  24. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  25. #include "network/HttpClient.h"
  26. #include <thread>
  27. #include <queue>
  28. #include <condition_variable>
  29. #include <errno.h>
  30. #include "base/CCVector.h"
  31. #include "base/CCDirector.h"
  32. #include "base/CCScheduler.h"
  33. #include "platform/CCFileUtils.h"
  34. #include "network/HttpConnection-winrt.h"
  35. NS_CC_BEGIN
  36. namespace network {
  37. static std::mutex s_requestQueueMutex;
  38. static std::mutex s_responseQueueMutex;
  39. static std::condition_variable_any s_SleepCondition;
  40. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
  41. typedef int int32_t;
  42. #endif
  43. static Vector<HttpRequest*>* s_requestQueue = nullptr;
  44. static Vector<HttpResponse*>* s_responseQueue = nullptr;
  45. static HttpClient *s_pHttpClient = nullptr; // pointer to singleton
  46. static std::string s_errorBuffer ="";
  47. static std::string s_cookieFilename = "";
  48. static std::string s_sslCaFilename = "";
  49. // function used to collect response/header data
  50. static void writeData(std::vector<char> *pFromBuffer, std::vector<char> *pToBuffer)
  51. {
  52. if(nullptr == pFromBuffer || nullptr == pToBuffer)
  53. return;
  54. pToBuffer->insert(pToBuffer->end(), pFromBuffer->begin(), pFromBuffer->end());
  55. }
  56. static void processHttpResponse(HttpResponse* response, std::string& errorStr);
  57. static HttpRequest *s_requestSentinel = new (std::nothrow) HttpRequest;
  58. // Worker thread
  59. void HttpClient::networkThread()
  60. {
  61. auto scheduler = Director::getInstance()->getScheduler();
  62. while (true)
  63. {
  64. HttpRequest *request;
  65. // step 1: send http request if the requestQueue isn't empty
  66. {
  67. std::lock_guard<std::mutex> lock(s_requestQueueMutex);
  68. while (s_requestQueue->empty()) {
  69. s_SleepCondition.wait(s_requestQueueMutex);
  70. }
  71. request = s_requestQueue->at(0);
  72. s_requestQueue->erase(0);
  73. }
  74. if (request == s_requestSentinel) {
  75. break;
  76. }
  77. // step 2: libcurl sync access
  78. // Create a HttpResponse object, the default setting is http access failed
  79. HttpResponse *response = new (std::nothrow) HttpResponse(request);
  80. processHttpResponse(response, s_errorBuffer);
  81. // add response packet into queue
  82. s_responseQueueMutex.lock();
  83. s_responseQueue->pushBack(response);
  84. s_responseQueueMutex.unlock();
  85. if (nullptr != s_pHttpClient) {
  86. scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
  87. }
  88. }
  89. // cleanup: if worker thread received quit signal, clean up un-completed request queue
  90. s_requestQueueMutex.lock();
  91. s_requestQueue->clear();
  92. s_requestQueueMutex.unlock();
  93. if (s_requestQueue != nullptr) {
  94. delete s_requestQueue;
  95. s_requestQueue = nullptr;
  96. delete s_responseQueue;
  97. s_responseQueue = nullptr;
  98. }
  99. }
  100. // Worker thread
  101. void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response)
  102. {
  103. std::string errorStr;
  104. processHttpResponse(response, errorStr);
  105. auto scheduler = Director::getInstance()->getScheduler();
  106. scheduler->performFunctionInCocosThread([response, request]{
  107. const ccHttpRequestCallback& callback = request->getCallback();
  108. Ref* pTarget = request->getTarget();
  109. SEL_HttpResponse pSelector = request->getSelector();
  110. if (callback != nullptr)
  111. {
  112. callback(s_pHttpClient, response);
  113. }
  114. else if (pTarget && pSelector)
  115. {
  116. (pTarget->*pSelector)(s_pHttpClient, response);
  117. }
  118. response->release();
  119. // do not release in other thread
  120. request->release();
  121. });
  122. }
  123. // Process Response
  124. static void processHttpResponse(HttpResponse* response, std::string& errorStr)
  125. {
  126. auto request = response->getHttpRequest();
  127. long responseCode = -1;
  128. int retValue = 0;
  129. HttpConnection xhr;
  130. bool ok = false;
  131. bool manualAuthReqd = false;
  132. // Process the request -> get response packet
  133. switch (request->getRequestType())
  134. {
  135. case HttpRequest::Type::GET: // HTTP GET
  136. ok = (xhr.init(request) && xhr.open("GET", manualAuthReqd, s_cookieFilename) && xhr.send());
  137. break;
  138. case HttpRequest::Type::POST: // HTTP POST
  139. ok = (xhr.init(request) && xhr.open("POST", manualAuthReqd, s_cookieFilename) && xhr.send());
  140. break;
  141. case HttpRequest::Type::PUT: // HTTP PUT
  142. ok = (xhr.init(request) && xhr.open("PUT", manualAuthReqd, s_cookieFilename) && xhr.send());
  143. break;
  144. case HttpRequest::Type::DELETE: // HTTP DELETE
  145. ok = (xhr.init(request) && xhr.open("DELETE", manualAuthReqd, s_cookieFilename) && xhr.send());
  146. break;
  147. default:
  148. CCASSERT(true, "CCHttpClient: unknown request type, only GET and POST are supported");
  149. break;
  150. }
  151. writeData(xhr.getResponseHeader(), response->getResponseHeader());
  152. writeData(xhr.getResponseData(), response->getResponseData());
  153. retValue = ok ? 0 : 1;
  154. errorStr = xhr.getErrorMessage();
  155. responseCode = xhr.getStatusCode();
  156. // write data to HttpResponse
  157. response->setResponseCode(responseCode);
  158. if (retValue != 0)
  159. {
  160. response->setSucceed(false);
  161. response->setErrorBuffer(errorStr.c_str());
  162. }
  163. else
  164. {
  165. response->setSucceed(true);
  166. }
  167. }
  168. // HttpClient implementation
  169. HttpClient* HttpClient::getInstance()
  170. {
  171. if (s_pHttpClient == nullptr) {
  172. s_pHttpClient = new (std::nothrow) HttpClient();
  173. }
  174. return s_pHttpClient;
  175. }
  176. void HttpClient::destroyInstance()
  177. {
  178. CC_SAFE_DELETE(s_pHttpClient);
  179. }
  180. void HttpClient::enableCookies(const char* cookieFile) {
  181. if (cookieFile) {
  182. s_cookieFilename = std::string(cookieFile);
  183. }
  184. else {
  185. s_cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
  186. }
  187. }
  188. void HttpClient::setSSLVerification(const std::string& caFile)
  189. {
  190. s_sslCaFilename = caFile;
  191. }
  192. HttpClient::HttpClient()
  193. : _timeoutForConnect(30)
  194. , _timeoutForRead(60)
  195. {
  196. }
  197. HttpClient::~HttpClient()
  198. {
  199. if (s_requestQueue != nullptr) {
  200. {
  201. std::lock_guard<std::mutex> lock(s_requestQueueMutex);
  202. s_requestQueue->pushBack(s_requestSentinel);
  203. }
  204. s_SleepCondition.notify_one();
  205. }
  206. s_pHttpClient = nullptr;
  207. }
  208. //Lazy create semaphore & mutex & thread
  209. bool HttpClient::lazyInitThreadSemaphore()
  210. {
  211. if (s_requestQueue != nullptr) {
  212. return true;
  213. }
  214. else {
  215. s_requestQueue = new (std::nothrow) Vector<HttpRequest*>();
  216. s_responseQueue = new (std::nothrow) Vector<HttpResponse*>();
  217. auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this));
  218. t.detach();
  219. }
  220. return true;
  221. }
  222. //Add a get task to queue
  223. void HttpClient::send(HttpRequest* request)
  224. {
  225. if (false == lazyInitThreadSemaphore())
  226. {
  227. return;
  228. }
  229. if (!request)
  230. {
  231. return;
  232. }
  233. request->retain();
  234. if (nullptr != s_requestQueue) {
  235. s_requestQueueMutex.lock();
  236. s_requestQueue->pushBack(request);
  237. s_requestQueueMutex.unlock();
  238. // Notify thread start to work
  239. s_SleepCondition.notify_one();
  240. }
  241. }
  242. void HttpClient::sendImmediate(HttpRequest* request)
  243. {
  244. if (!request)
  245. {
  246. return;
  247. }
  248. request->retain();
  249. // Create a HttpResponse object, the default setting is http access failed
  250. HttpResponse *response = new (std::nothrow) HttpResponse(request);
  251. auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response);
  252. t.detach();
  253. }
  254. // Poll and notify main thread if responses exists in queue
  255. void HttpClient::dispatchResponseCallbacks()
  256. {
  257. // log("CCHttpClient::dispatchResponseCallbacks is running");
  258. //occurs when cocos thread fires but the network thread has already quited
  259. if (nullptr == s_responseQueue) {
  260. return;
  261. }
  262. HttpResponse* response = nullptr;
  263. s_responseQueueMutex.lock();
  264. if (!s_responseQueue->empty())
  265. {
  266. response = s_responseQueue->at(0);
  267. s_responseQueue->erase(0);
  268. }
  269. s_responseQueueMutex.unlock();
  270. if (response)
  271. {
  272. HttpRequest *request = response->getHttpRequest();
  273. const ccHttpRequestCallback& callback = request->getCallback();
  274. Ref* pTarget = request->getTarget();
  275. SEL_HttpResponse pSelector = request->getSelector();
  276. if (callback != nullptr)
  277. {
  278. callback(this, response);
  279. }
  280. else if (pTarget && pSelector)
  281. {
  282. (pTarget->*pSelector)(this, response);
  283. }
  284. response->release();
  285. // do not release in other thread
  286. request->release();
  287. }
  288. }
  289. }
  290. NS_CC_END
  291. #endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)