2014-12-31 10:02:14 +08:00
|
|
|
/****************************************************************************
|
|
|
|
Copyright (c) 2012 greathqy
|
|
|
|
Copyright (c) 2012 cocos2d-x.org
|
2016-05-18 12:54:16 +08:00
|
|
|
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
http://www.cocos2d-x.org
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
|
|
of this software and associated documentation files (the "Software"), to deal
|
|
|
|
in the Software without restriction, including without limitation the rights
|
|
|
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
|
|
copies of the Software, and to permit persons to whom the Software is
|
|
|
|
furnished to do so, subject to the following conditions:
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
The above copyright notice and this permission notice shall be included in
|
|
|
|
all copies or substantial portions of the Software.
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
|
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
|
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
|
|
THE SOFTWARE.
|
|
|
|
****************************************************************************/
|
|
|
|
|
2015-08-13 15:14:10 +08:00
|
|
|
#include "platform/CCPlatformConfig.h"
|
|
|
|
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
|
|
|
|
|
2016-05-25 23:57:40 +08:00
|
|
|
#include "network/HttpClient.h"
|
2014-12-31 10:02:14 +08:00
|
|
|
|
|
|
|
#include <queue>
|
|
|
|
#include <errno.h>
|
|
|
|
|
2015-08-13 15:14:10 +08:00
|
|
|
#import "network/HttpAsynConnection-apple.h"
|
2015-05-22 10:47:52 +08:00
|
|
|
#include "network/HttpCookie.h"
|
2014-12-31 10:02:14 +08:00
|
|
|
#include "base/CCDirector.h"
|
|
|
|
#include "platform/CCFileUtils.h"
|
|
|
|
|
|
|
|
NS_CC_BEGIN
|
|
|
|
|
|
|
|
namespace network {
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
static HttpClient *_httpClient = nullptr; // pointer to singleton
|
2014-12-31 10:02:14 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
static int processTask(HttpClient* client, HttpRequest *request, NSString *requestType, void *stream, long *errorCode, void *headerStream, char *errorBuffer);
|
2014-12-31 10:02:14 +08:00
|
|
|
|
|
|
|
// Worker thread
|
|
|
|
void HttpClient::networkThread()
|
2015-05-22 10:47:52 +08:00
|
|
|
{
|
|
|
|
increaseThreadCount();
|
2014-12-31 10:02:14 +08:00
|
|
|
|
Fix major memory leaks in iOS http request
... and other small fixes
Brief:
1. In iOS, whenever you have a new spawned thread with its own run loop (i.e. while true), you must wrap it with an autorelease pool, so it cleans up the objects at the end of each loop cycle.
2. There were a few "alloc" and "new" objects that weren't released.
3. The HttpAsync class itself was missing dealloc, also property assignment should use `self.property` so the previous value gets released as appropriate.
4. Resolved a small warning
**NOTE**: I have a cocos2d-x game that heavily relies on the HTTP requests, with cookies, but without SSL, so I couldn't test the SSL.
I haven't tested the cookies and SSL yet, but for starters, these improvements are meant to fix the memory issues only, not the logic.
2015-02-23 14:38:33 +08:00
|
|
|
while (true) @autoreleasepool {
|
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
HttpRequest *request;
|
|
|
|
|
|
|
|
// step 1: send http request if the requestQueue isn't empty
|
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
std::lock_guard<std::mutex> lock(_requestQueueMutex);
|
|
|
|
while (_requestQueue.empty()) {
|
|
|
|
_sleepCondition.wait(_requestQueueMutex);
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2015-05-22 10:47:52 +08:00
|
|
|
request = _requestQueue.at(0);
|
|
|
|
_requestQueue.erase(0);
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
if (request == _requestSentinel) {
|
2014-12-31 10:02:14 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a HttpResponse object, the default setting is http access failed
|
|
|
|
HttpResponse *response = new (std::nothrow) HttpResponse(request);
|
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
processResponse(response, _responseMessage);
|
2014-12-31 10:02:14 +08:00
|
|
|
|
|
|
|
// add response packet into queue
|
2015-05-22 10:47:52 +08:00
|
|
|
_responseQueueMutex.lock();
|
|
|
|
_responseQueue.pushBack(response);
|
|
|
|
_responseQueueMutex.unlock();
|
2014-12-31 10:02:14 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
_schedulerMutex.lock();
|
|
|
|
if (nullptr != _scheduler)
|
|
|
|
{
|
|
|
|
_scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2015-05-22 10:47:52 +08:00
|
|
|
_schedulerMutex.unlock();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// cleanup: if worker thread received quit signal, clean up un-completed request queue
|
2015-05-22 10:47:52 +08:00
|
|
|
_requestQueueMutex.lock();
|
|
|
|
_requestQueue.clear();
|
|
|
|
_requestQueueMutex.unlock();
|
2014-12-31 10:02:14 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
_responseQueueMutex.lock();
|
|
|
|
_responseQueue.clear();
|
|
|
|
_responseQueueMutex.unlock();
|
2014-12-31 10:02:14 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
decreaseThreadCountAndMayDeleteThis();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Worker thread
|
2015-02-02 11:23:15 +08:00
|
|
|
void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response)
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
increaseThreadCount();
|
|
|
|
|
|
|
|
char responseMessage[RESPONSE_BUFFER_SIZE] = { 0 };
|
|
|
|
processResponse(response, responseMessage);
|
|
|
|
|
|
|
|
_schedulerMutex.lock();
|
|
|
|
if (nullptr != _scheduler)
|
|
|
|
{
|
|
|
|
_scheduler->performFunctionInCocosThread([this, response, request]{
|
|
|
|
const ccHttpRequestCallback& callback = request->getCallback();
|
|
|
|
Ref* pTarget = request->getTarget();
|
|
|
|
SEL_HttpResponse pSelector = request->getSelector();
|
|
|
|
|
|
|
|
if (callback != nullptr)
|
|
|
|
{
|
|
|
|
callback(this, response);
|
|
|
|
}
|
|
|
|
else if (pTarget && pSelector)
|
|
|
|
{
|
|
|
|
(pTarget->*pSelector)(this, response);
|
|
|
|
}
|
|
|
|
response->release();
|
|
|
|
// do not release in other thread
|
|
|
|
request->release();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
_schedulerMutex.unlock();
|
|
|
|
decreaseThreadCountAndMayDeleteThis();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
//Process Request
|
2015-05-22 10:47:52 +08:00
|
|
|
static int processTask(HttpClient* client, HttpRequest* request, NSString* requestType, void* stream, long* responseCode, void* headerStream, char* errorBuffer)
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
if (nullptr == client)
|
|
|
|
{
|
|
|
|
strcpy(errorBuffer, "client object is invalid");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
//create request with url
|
|
|
|
NSString* urlstring = [NSString stringWithUTF8String:request->getUrl()];
|
|
|
|
NSURL *url = [NSURL URLWithString:urlstring];
|
|
|
|
|
|
|
|
NSMutableURLRequest *nsrequest = [NSMutableURLRequest requestWithURL:url
|
|
|
|
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
|
|
|
|
timeoutInterval:HttpClient::getInstance()->getTimeoutForConnect()];
|
|
|
|
|
|
|
|
//set request type
|
|
|
|
[nsrequest setHTTPMethod:requestType];
|
|
|
|
|
2015-02-12 19:07:19 +08:00
|
|
|
/* get custom header data (if set) */
|
|
|
|
std::vector<std::string> headers=request->getHeaders();
|
|
|
|
if(!headers.empty())
|
|
|
|
{
|
|
|
|
/* append custom headers one by one */
|
2016-10-27 15:10:24 +08:00
|
|
|
for (auto& header : headers)
|
2015-02-12 19:07:19 +08:00
|
|
|
{
|
2016-10-27 15:10:24 +08:00
|
|
|
unsigned long i = header.find(':', 0);
|
|
|
|
unsigned long length = header.size();
|
|
|
|
std::string field = header.substr(0, i);
|
|
|
|
std::string value = header.substr(i+1, length-i);
|
2015-02-12 19:07:19 +08:00
|
|
|
NSString *headerField = [NSString stringWithUTF8String:field.c_str()];
|
|
|
|
NSString *headerValue = [NSString stringWithUTF8String:value.c_str()];
|
|
|
|
[nsrequest setValue:headerValue forHTTPHeaderField:headerField];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
//if request type is post or put,set header and data
|
|
|
|
if([requestType isEqual: @"POST"] || [requestType isEqual: @"PUT"])
|
2016-05-10 18:15:57 +08:00
|
|
|
{
|
2015-01-04 17:09:35 +08:00
|
|
|
char* requestDataBuffer = request->getRequestData();
|
2015-02-18 15:45:43 +08:00
|
|
|
if (nullptr != requestDataBuffer && 0 != request->getRequestDataSize())
|
2015-01-04 17:09:35 +08:00
|
|
|
{
|
2015-01-31 14:31:24 +08:00
|
|
|
NSData *postData = [NSData dataWithBytes:requestDataBuffer length:request->getRequestDataSize()];
|
2015-01-04 17:09:35 +08:00
|
|
|
[nsrequest setHTTPBody:postData];
|
|
|
|
}
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
2016-03-29 09:52:17 +08:00
|
|
|
//read cookie properties from file and set cookie
|
2015-05-22 10:47:52 +08:00
|
|
|
std::string cookieFilename = client->getCookieFilename();
|
|
|
|
if(!cookieFilename.empty() && nullptr != client->getCookie())
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
const CookiesInfo* cookieInfo = client->getCookie()->getMatchCookie(request->getUrl());
|
2014-12-31 10:02:14 +08:00
|
|
|
if(cookieInfo != nullptr)
|
|
|
|
{
|
|
|
|
NSString *domain = [NSString stringWithCString:cookieInfo->domain.c_str() encoding:[NSString defaultCStringEncoding]];
|
|
|
|
NSString *path = [NSString stringWithCString:cookieInfo->path.c_str() encoding:[NSString defaultCStringEncoding]];
|
|
|
|
NSString *value = [NSString stringWithCString:cookieInfo->value.c_str() encoding:[NSString defaultCStringEncoding]];
|
|
|
|
NSString *name = [NSString stringWithCString:cookieInfo->name.c_str() encoding:[NSString defaultCStringEncoding]];
|
|
|
|
|
|
|
|
// create the properties for a cookie
|
|
|
|
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys: name,NSHTTPCookieName,
|
|
|
|
value, NSHTTPCookieValue, path, NSHTTPCookiePath,
|
|
|
|
domain, NSHTTPCookieDomain,
|
|
|
|
nil];
|
|
|
|
|
|
|
|
// create the cookie from the properties
|
|
|
|
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
|
|
|
|
|
|
|
|
// add the cookie to the cookie storage
|
|
|
|
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Fix major memory leaks in iOS http request
... and other small fixes
Brief:
1. In iOS, whenever you have a new spawned thread with its own run loop (i.e. while true), you must wrap it with an autorelease pool, so it cleans up the objects at the end of each loop cycle.
2. There were a few "alloc" and "new" objects that weren't released.
3. The HttpAsync class itself was missing dealloc, also property assignment should use `self.property` so the previous value gets released as appropriate.
4. Resolved a small warning
**NOTE**: I have a cocos2d-x game that heavily relies on the HTTP requests, with cookies, but without SSL, so I couldn't test the SSL.
I haven't tested the cookies and SSL yet, but for starters, these improvements are meant to fix the memory issues only, not the logic.
2015-02-23 14:38:33 +08:00
|
|
|
HttpAsynConnection *httpAsynConn = [[HttpAsynConnection new] autorelease];
|
2014-12-31 10:02:14 +08:00
|
|
|
httpAsynConn.srcURL = urlstring;
|
|
|
|
httpAsynConn.sslFile = nil;
|
Fix major memory leaks in iOS http request
... and other small fixes
Brief:
1. In iOS, whenever you have a new spawned thread with its own run loop (i.e. while true), you must wrap it with an autorelease pool, so it cleans up the objects at the end of each loop cycle.
2. There were a few "alloc" and "new" objects that weren't released.
3. The HttpAsync class itself was missing dealloc, also property assignment should use `self.property` so the previous value gets released as appropriate.
4. Resolved a small warning
**NOTE**: I have a cocos2d-x game that heavily relies on the HTTP requests, with cookies, but without SSL, so I couldn't test the SSL.
I haven't tested the cookies and SSL yet, but for starters, these improvements are meant to fix the memory issues only, not the logic.
2015-02-23 14:38:33 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
std::string sslCaFileName = client->getSSLVerification();
|
|
|
|
if(!sslCaFileName.empty())
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
long len = sslCaFileName.length();
|
|
|
|
long pos = sslCaFileName.rfind('.', len-1);
|
Fix major memory leaks in iOS http request
... and other small fixes
Brief:
1. In iOS, whenever you have a new spawned thread with its own run loop (i.e. while true), you must wrap it with an autorelease pool, so it cleans up the objects at the end of each loop cycle.
2. There were a few "alloc" and "new" objects that weren't released.
3. The HttpAsync class itself was missing dealloc, also property assignment should use `self.property` so the previous value gets released as appropriate.
4. Resolved a small warning
**NOTE**: I have a cocos2d-x game that heavily relies on the HTTP requests, with cookies, but without SSL, so I couldn't test the SSL.
I haven't tested the cookies and SSL yet, but for starters, these improvements are meant to fix the memory issues only, not the logic.
2015-02-23 14:38:33 +08:00
|
|
|
|
2015-05-29 17:13:49 +08:00
|
|
|
httpAsynConn.sslFile = [NSString stringWithUTF8String:sslCaFileName.substr(0, pos).c_str()];
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
[httpAsynConn startRequest:nsrequest];
|
|
|
|
|
|
|
|
while( httpAsynConn.finish != true)
|
|
|
|
{
|
|
|
|
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
|
|
|
|
}
|
|
|
|
|
|
|
|
//if http connection return error
|
2015-03-03 15:33:35 +08:00
|
|
|
if (httpAsynConn.connError != nil)
|
|
|
|
{
|
|
|
|
NSString* errorString = [httpAsynConn.connError localizedDescription];
|
|
|
|
strcpy(errorBuffer, [errorString UTF8String]);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
//if http response got error, just log the error
|
2014-12-31 10:02:14 +08:00
|
|
|
if (httpAsynConn.responseError != nil)
|
|
|
|
{
|
|
|
|
NSString* errorString = [httpAsynConn.responseError localizedDescription];
|
|
|
|
strcpy(errorBuffer, [errorString UTF8String]);
|
|
|
|
}
|
|
|
|
|
|
|
|
*responseCode = httpAsynConn.responseCode;
|
|
|
|
|
|
|
|
//add cookie to cookies vector
|
2015-05-22 10:47:52 +08:00
|
|
|
if(!cookieFilename.empty())
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
|
|
|
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:httpAsynConn.responseHeader forURL:url];
|
|
|
|
for (NSHTTPCookie *cookie in cookies)
|
|
|
|
{
|
|
|
|
//NSLog(@"Cookie: %@", cookie);
|
|
|
|
NSString *domain = cookie.domain;
|
|
|
|
//BOOL session = cookie.sessionOnly;
|
|
|
|
NSString *path = cookie.path;
|
2015-01-04 13:49:41 +08:00
|
|
|
BOOL secure = cookie.isSecure;
|
2014-12-31 10:02:14 +08:00
|
|
|
NSDate *date = cookie.expiresDate;
|
|
|
|
NSString *name = cookie.name;
|
|
|
|
NSString *value = cookie.value;
|
|
|
|
|
|
|
|
CookiesInfo cookieInfo;
|
|
|
|
cookieInfo.domain = [domain cStringUsingEncoding: NSUTF8StringEncoding];
|
|
|
|
cookieInfo.path = [path cStringUsingEncoding: NSUTF8StringEncoding];
|
|
|
|
cookieInfo.secure = (secure == YES) ? true : false;
|
|
|
|
cookieInfo.expires = [[NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]] cStringUsingEncoding: NSUTF8StringEncoding];
|
|
|
|
cookieInfo.name = [name cStringUsingEncoding: NSUTF8StringEncoding];
|
|
|
|
cookieInfo.value = [value cStringUsingEncoding: NSUTF8StringEncoding];
|
|
|
|
cookieInfo.tailmatch = true;
|
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
client->getCookie()->updateOrAddCookie(&cookieInfo);
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//handle response header
|
2015-02-25 14:56:25 +08:00
|
|
|
NSMutableString *header = [NSMutableString string];
|
Fix major memory leaks in iOS http request
... and other small fixes
Brief:
1. In iOS, whenever you have a new spawned thread with its own run loop (i.e. while true), you must wrap it with an autorelease pool, so it cleans up the objects at the end of each loop cycle.
2. There were a few "alloc" and "new" objects that weren't released.
3. The HttpAsync class itself was missing dealloc, also property assignment should use `self.property` so the previous value gets released as appropriate.
4. Resolved a small warning
**NOTE**: I have a cocos2d-x game that heavily relies on the HTTP requests, with cookies, but without SSL, so I couldn't test the SSL.
I haven't tested the cookies and SSL yet, but for starters, these improvements are meant to fix the memory issues only, not the logic.
2015-02-23 14:38:33 +08:00
|
|
|
[header appendFormat:@"HTTP/1.1 %ld %@\n", (long)httpAsynConn.responseCode, httpAsynConn.statusString];
|
2014-12-31 10:02:14 +08:00
|
|
|
for (id key in httpAsynConn.responseHeader)
|
|
|
|
{
|
|
|
|
[header appendFormat:@"%@: %@\n", key, [httpAsynConn.responseHeader objectForKey:key]];
|
|
|
|
}
|
|
|
|
if (header.length > 0)
|
|
|
|
{
|
|
|
|
NSRange range = NSMakeRange(header.length-1, 1);
|
|
|
|
[header deleteCharactersInRange:range];
|
|
|
|
}
|
|
|
|
NSData *headerData = [header dataUsingEncoding:NSUTF8StringEncoding];
|
|
|
|
std::vector<char> *headerBuffer = (std::vector<char>*)headerStream;
|
|
|
|
const void* headerptr = [headerData bytes];
|
|
|
|
long headerlen = [headerData length];
|
|
|
|
headerBuffer->insert(headerBuffer->end(), (char*)headerptr, (char*)headerptr+headerlen);
|
|
|
|
|
|
|
|
//handle response data
|
|
|
|
std::vector<char> *recvBuffer = (std::vector<char>*)stream;
|
|
|
|
const void* ptr = [httpAsynConn.responseData bytes];
|
|
|
|
long len = [httpAsynConn.responseData length];
|
|
|
|
recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+len);
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
// HttpClient implementation
|
|
|
|
HttpClient* HttpClient::getInstance()
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
if (_httpClient == nullptr)
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
_httpClient = new (std::nothrow) HttpClient();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
return _httpClient;
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
void HttpClient::destroyInstance()
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
if (nullptr == _httpClient)
|
|
|
|
{
|
|
|
|
CCLOG("HttpClient singleton is nullptr");
|
|
|
|
return;
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
CCLOG("HttpClient::destroyInstance begin");
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
auto thiz = _httpClient;
|
|
|
|
_httpClient = nullptr;
|
|
|
|
|
|
|
|
thiz->_scheduler->unscheduleAllForTarget(thiz);
|
|
|
|
thiz->_schedulerMutex.lock();
|
|
|
|
thiz->_scheduler = nullptr;
|
|
|
|
thiz->_schedulerMutex.unlock();
|
|
|
|
|
|
|
|
thiz->_requestQueueMutex.lock();
|
|
|
|
thiz->_requestQueue.pushBack(thiz->_requestSentinel);
|
|
|
|
thiz->_requestQueueMutex.unlock();
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
thiz->_sleepCondition.notify_one();
|
|
|
|
thiz->decreaseThreadCountAndMayDeleteThis();
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
CCLOG("HttpClient::destroyInstance() finished!");
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
void HttpClient::enableCookies(const char* cookieFile)
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
_cookieFileMutex.lock();
|
|
|
|
if (cookieFile)
|
|
|
|
{
|
|
|
|
_cookieFilename = std::string(cookieFile);
|
|
|
|
_cookieFilename = FileUtils::getInstance()->fullPathForFilename(_cookieFilename);
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2015-05-22 10:47:52 +08:00
|
|
|
else
|
|
|
|
{
|
|
|
|
_cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2015-05-22 10:47:52 +08:00
|
|
|
_cookieFileMutex.unlock();
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
if (nullptr == _cookie)
|
|
|
|
{
|
|
|
|
_cookie = new(std::nothrow)HttpCookie;
|
|
|
|
}
|
|
|
|
_cookie->setCookieFileName(_cookieFilename);
|
|
|
|
_cookie->readFile();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
void HttpClient::setSSLVerification(const std::string& caFile)
|
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
std::lock_guard<std::mutex> lock(_sslCaFileMutex);
|
|
|
|
_sslCaFilename = caFile;
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
HttpClient::HttpClient()
|
2017-02-04 09:46:32 +08:00
|
|
|
: _isInited(false)
|
|
|
|
, _timeoutForConnect(30)
|
2014-12-31 10:02:14 +08:00
|
|
|
, _timeoutForRead(60)
|
2015-05-22 10:47:52 +08:00
|
|
|
, _threadCount(0)
|
|
|
|
, _cookie(nullptr)
|
2017-02-04 09:46:32 +08:00
|
|
|
, _requestSentinel(new HttpRequest())
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
CCLOG("In the constructor of HttpClient!");
|
|
|
|
memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE);
|
|
|
|
_scheduler = Director::getInstance()->getScheduler();
|
|
|
|
increaseThreadCount();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
|
|
|
|
HttpClient::~HttpClient()
|
|
|
|
{
|
2016-05-25 13:54:13 +08:00
|
|
|
CC_SAFE_RELEASE(_requestSentinel);
|
2015-05-22 10:47:52 +08:00
|
|
|
if (!_cookieFilename.empty() && nullptr != _cookie)
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
_cookie->writeFile();
|
|
|
|
CC_SAFE_DELETE(_cookie);
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2015-05-22 10:47:52 +08:00
|
|
|
CCLOG("HttpClient destructor");
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
//Lazy create semaphore & mutex & thread
|
2017-01-18 15:40:46 +08:00
|
|
|
bool HttpClient::lazyInitThreadSemaphore()
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
if (_isInited)
|
|
|
|
{
|
2014-12-31 10:02:14 +08:00
|
|
|
return true;
|
2015-05-22 10:47:52 +08:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2014-12-31 10:02:14 +08:00
|
|
|
auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this));
|
|
|
|
t.detach();
|
2015-05-22 10:47:52 +08:00
|
|
|
_isInited = true;
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Add a get task to queue
|
|
|
|
void HttpClient::send(HttpRequest* request)
|
2016-05-18 12:54:16 +08:00
|
|
|
{
|
2017-01-18 15:40:46 +08:00
|
|
|
if (false == lazyInitThreadSemaphore())
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
if (!request)
|
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
request->retain();
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
_requestQueueMutex.lock();
|
|
|
|
_requestQueue.pushBack(request);
|
|
|
|
_requestQueueMutex.unlock();
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
// Notify thread start to work
|
|
|
|
_sleepCondition.notify_one();
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void HttpClient::sendImmediate(HttpRequest* request)
|
|
|
|
{
|
|
|
|
if(!request)
|
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
request->retain();
|
2015-02-02 11:23:15 +08:00
|
|
|
// Create a HttpResponse object, the default setting is http access failed
|
|
|
|
HttpResponse *response = new (std::nothrow) HttpResponse(request);
|
|
|
|
|
|
|
|
auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response);
|
2014-12-31 10:02:14 +08:00
|
|
|
t.detach();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Poll and notify main thread if responses exists in queue
|
|
|
|
void HttpClient::dispatchResponseCallbacks()
|
|
|
|
{
|
|
|
|
// log("CCHttpClient::dispatchResponseCallbacks is running");
|
|
|
|
//occurs when cocos thread fires but the network thread has already quited
|
|
|
|
HttpResponse* response = nullptr;
|
2015-05-22 10:47:52 +08:00
|
|
|
_responseQueueMutex.lock();
|
|
|
|
if (!_responseQueue.empty())
|
2014-12-31 10:02:14 +08:00
|
|
|
{
|
2015-05-22 10:47:52 +08:00
|
|
|
response = _responseQueue.at(0);
|
|
|
|
_responseQueue.erase(0);
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
2015-05-22 10:47:52 +08:00
|
|
|
_responseQueueMutex.unlock();
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
if (response)
|
|
|
|
{
|
|
|
|
HttpRequest *request = response->getHttpRequest();
|
|
|
|
const ccHttpRequestCallback& callback = request->getCallback();
|
|
|
|
Ref* pTarget = request->getTarget();
|
|
|
|
SEL_HttpResponse pSelector = request->getSelector();
|
|
|
|
|
|
|
|
if (callback != nullptr)
|
|
|
|
{
|
|
|
|
callback(this, response);
|
|
|
|
}
|
|
|
|
else if (pTarget && pSelector)
|
|
|
|
{
|
|
|
|
(pTarget->*pSelector)(this, response);
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
response->release();
|
|
|
|
// do not release in other thread
|
|
|
|
request->release();
|
|
|
|
}
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
// Process Response
|
|
|
|
void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
|
|
|
|
{
|
|
|
|
auto request = response->getHttpRequest();
|
|
|
|
long responseCode = -1;
|
|
|
|
int retValue = 0;
|
|
|
|
NSString* requestType = nil;
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
// Process the request -> get response packet
|
|
|
|
switch (request->getRequestType())
|
|
|
|
{
|
|
|
|
case HttpRequest::Type::GET: // HTTP GET
|
|
|
|
requestType = @"GET";
|
|
|
|
break;
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
case HttpRequest::Type::POST: // HTTP POST
|
|
|
|
requestType = @"POST";
|
|
|
|
break;
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
case HttpRequest::Type::PUT:
|
|
|
|
requestType = @"PUT";
|
|
|
|
break;
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
case HttpRequest::Type::DELETE:
|
|
|
|
requestType = @"DELETE";
|
|
|
|
break;
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
default:
|
|
|
|
CCASSERT(true, "CCHttpClient: unknown request type, only GET and POSt are supported");
|
|
|
|
break;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
retValue = processTask(this,
|
|
|
|
request,
|
|
|
|
requestType,
|
|
|
|
response->getResponseData(),
|
|
|
|
&responseCode,
|
|
|
|
response->getResponseHeader(),
|
|
|
|
responseMessage);
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
// write data to HttpResponse
|
|
|
|
response->setResponseCode(responseCode);
|
2016-05-18 12:54:16 +08:00
|
|
|
|
|
|
|
if (retValue != 0)
|
2015-05-22 10:47:52 +08:00
|
|
|
{
|
|
|
|
response->setSucceed(true);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
response->setSucceed(false);
|
|
|
|
response->setErrorBuffer(responseMessage);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
void HttpClient::increaseThreadCount()
|
|
|
|
{
|
|
|
|
_threadCountMutex.lock();
|
|
|
|
++_threadCount;
|
|
|
|
_threadCountMutex.unlock();
|
|
|
|
}
|
2014-12-31 10:02:14 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
void HttpClient::decreaseThreadCountAndMayDeleteThis()
|
|
|
|
{
|
|
|
|
bool needDeleteThis = false;
|
|
|
|
_threadCountMutex.lock();
|
|
|
|
--_threadCount;
|
|
|
|
if (0 == _threadCount)
|
|
|
|
{
|
|
|
|
needDeleteThis = true;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
_threadCountMutex.unlock();
|
|
|
|
if (needDeleteThis)
|
|
|
|
{
|
|
|
|
delete this;
|
|
|
|
}
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
void HttpClient::setTimeoutForConnect(int value)
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
|
|
|
|
_timeoutForConnect = value;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
int HttpClient::getTimeoutForConnect()
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
|
|
|
|
return _timeoutForConnect;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
void HttpClient::setTimeoutForRead(int value)
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
|
|
|
|
_timeoutForRead = value;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
int HttpClient::getTimeoutForRead()
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
|
|
|
|
return _timeoutForRead;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
const std::string& HttpClient::getCookieFilename()
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock(_cookieFileMutex);
|
|
|
|
return _cookieFilename;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2015-05-22 10:47:52 +08:00
|
|
|
const std::string& HttpClient::getSSLVerification()
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lock(_sslCaFileMutex);
|
|
|
|
return _sslCaFilename;
|
|
|
|
}
|
2016-05-18 12:54:16 +08:00
|
|
|
|
2014-12-31 10:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
NS_CC_END
|
|
|
|
|
2015-08-13 15:14:10 +08:00
|
|
|
#endif // #if CC_TARGET_PLATFORM == CC_PLATFORM_MAC
|
|
|
|
|