Merge pull request #805 from dumganhar/jsb2.0

Merge V1.6 branch
This commit is contained in:
James Chen
2017-09-07 20:45:21 -05:00
committed by GitHub
30 changed files with 402 additions and 289 deletions
+1 -1
View File
@@ -801,7 +801,7 @@ public:
/** Remove proxy for a native object
*/
virtual void removeObjectProxy(Ref* obj) {}
virtual void removeObjectProxy(void* obj) {}
/** Triggers the garbage collector */
virtual void garbageCollect() {}
+42 -9
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -27,6 +27,8 @@
#include "network/CCDownloader.h"
#include "platform/android/jni/JniHelper.h"
#include <mutex>
#define JCLS_DOWNLOADER "org/cocos2dx/lib/Cocos2dxDownloader"
#define JCLS_TASK "com/loopj/android/http/RequestHandle"
#define JARG_STR "Ljava/lang/String;"
@@ -38,6 +40,33 @@ using namespace std;
static bool _registerNativeMethods(JNIEnv* env);
unordered_map<int, cocos2d::network::DownloaderAndroid*> sDownloaderMap;
std::mutex sDownloaderMutex;
static void _insertDownloaderAndroid(int id, cocos2d::network::DownloaderAndroid* downloaderPtr)
{
std::lock_guard<std::mutex> guard(sDownloaderMutex);
sDownloaderMap.insert(make_pair(id, downloaderPtr));
}
static void _eraseDownloaderAndroid(int id)
{
std::lock_guard<std::mutex> guard(sDownloaderMutex);
sDownloaderMap.erase(id);
}
/**
* If not found, return nullptr, otherwise return the Downloader
*/
static cocos2d::network::DownloaderAndroid* _findDownloaderAndroid(int id)
{
std::lock_guard<std::mutex> guard(sDownloaderMutex);
auto iter = sDownloaderMap.find(id);
if (sDownloaderMap.end() == iter) {
return nullptr;
} else {
return iter->second;
}
}
namespace cocos2d { namespace network {
@@ -83,7 +112,9 @@ namespace cocos2d { namespace network {
);
_impl = methodInfo.env->NewGlobalRef(jObj);
DLLOG("android downloader: jObj: %p, _impl: %p", jObj, _impl);
sDownloaderMap.insert(make_pair(_id, this));
//It's not thread-safe here, use thread-safe method instead
//sDownloaderMap.insert(make_pair(_id, this));
_insertDownloaderAndroid(_id, this);
methodInfo.env->DeleteLocalRef(jStr);
methodInfo.env->DeleteLocalRef(jObj);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
@@ -107,7 +138,9 @@ namespace cocos2d { namespace network {
);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
sDownloaderMap.erase(_id);
//It's not thread-safe here, use thread-safe method instead
//sDownloaderMap.erase(_id);
_eraseDownloaderAndroid(_id);
JniHelper::getEnv()->DeleteGlobalRef(_impl);
}
DLLOG("Destruct DownloaderAndroid: %p", this);
@@ -186,26 +219,26 @@ namespace cocos2d { namespace network {
static void _nativeOnProgress(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal)
{
DLLOG("_nativeOnProgress(id: %d, taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", id, taskId, dl, dlnow, dltotal);
auto iter = sDownloaderMap.find(id);
if (sDownloaderMap.end() == iter)
//It's not thread-safe here, use thread-safe method instead
cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id);
if (nullptr == downloader)
{
DLLOG("_nativeOnProgress can't find downloader by key: %p for task: %d", clazz, id);
return;
}
cocos2d::network::DownloaderAndroid *downloader = iter->second;
downloader->_onProcess((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal);
}
static void _nativeOnFinish(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data)
{
DLLOG("_nativeOnFinish(id: %d, taskId: %d)", id, taskId);
auto iter = sDownloaderMap.find(id);
if (sDownloaderMap.end() == iter)
//It's not thread-safe here, use thread-safe method instead
cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id);
if (nullptr == downloader)
{
DLLOG("_nativeOnFinish can't find downloader id: %d for task: %d", id, taskId);
return;
}
cocos2d::network::DownloaderAndroid *downloader = iter->second;
vector<unsigned char> buf;
if (errStr)
{
+1 -1
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
+1 -1
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
+19 -11
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -30,7 +30,7 @@
////////////////////////////////////////////////////////////////////////////////
// OC Classes Declaration
#import <Foundation/NSData.h>
#import <Foundation/Foundation.h>
// this wrapper used to wrap C++ class DownloadTask into NSMutableDictionary
@interface DownloadTaskWrapper : NSObject
@@ -227,7 +227,9 @@ namespace cocos2d { namespace network {
request = [NSURLRequest requestWithURL:url];
}
NSURLSessionDataTask *ocTask = [self.downloadSession dataTaskWithRequest:request];
[self.taskDict setObject:[[DownloadTaskWrapper alloc] init:task] forKey:ocTask];
DownloadTaskWrapper* taskWrapper = [[DownloadTaskWrapper alloc] init:task];
[self.taskDict setObject:taskWrapper forKey:ocTask];
[taskWrapper release];
if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
[ocTask resume];
@@ -263,7 +265,10 @@ namespace cocos2d { namespace network {
{
ocTask = [self.downloadSession downloadTaskWithRequest:request];
}
[self.taskDict setObject:[[DownloadTaskWrapper alloc] init:task] forKey:ocTask];
DownloadTaskWrapper* taskWrapper = [[DownloadTaskWrapper alloc] init:task];
[self.taskDict setObject:taskWrapper forKey:ocTask];
[taskWrapper release];
if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
[ocTask resume];
@@ -321,15 +326,19 @@ namespace cocos2d { namespace network {
}
}
_outer = nullptr;
while(!_taskQueue.empty())
_taskQueue.pop();
[self.downloadSession invalidateAndCancel];
[self release];
}
-(void)dealloc
{
[super dealloc];
DLLOG("Destruct DownloaderAppleImpl %p", self);
self.downloadSession = nil;
[super dealloc];
}
#pragma mark - NSURLSessionTaskDelegate methods
@@ -405,9 +414,9 @@ namespace cocos2d { namespace network {
std::string errorString;
const int64_t buflen = [wrapper totalBytesReceived];
char buf[buflen];
std::vector<unsigned char> data((size_t)buflen);
char* buf = (char*)data.data();
[wrapper transferDataToBuffer:buf lengthOfBuffer:buflen];
std::vector<unsigned char> data(buf, buf + buflen);
_outer->onTaskFinish(*[wrapper get],
cocos2d::network::DownloadTask::ERROR_NO_ERROR,
@@ -423,8 +432,8 @@ namespace cocos2d { namespace network {
if (statusCode >= 400)
{
std::vector<unsigned char> buf; // just a placeholder
const char *orignalURL = [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding];
std::string errorMessage = cocos2d::StringUtils::format("Downloader: Failed to download %s with status code (%d)", orignalURL, (int)statusCode);
const char *originalURL = [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding];
std::string errorMessage = cocos2d::StringUtils::format("Downloader: Failed to download %s with status code (%d)", originalURL, (int)statusCode);
_outer->onTaskFinish(*[wrapper get],
cocos2d::network::DownloadTask::ERROR_IMPL_INTERNAL,
@@ -435,7 +444,6 @@ namespace cocos2d { namespace network {
}
}
[self.taskDict removeObjectForKey:task];
[wrapper release];
while (!_taskQueue.empty() && _taskQueue.front() == nil) {
_taskQueue.pop();
+3 -2
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -624,7 +624,8 @@ namespace cocos2d { namespace network {
}
// process tasks in _requestList
while (0 == countOfMaxProcessingTasks || coTaskMap.size() < countOfMaxProcessingTasks)
auto size = coTaskMap.size();
while (0 == countOfMaxProcessingTasks || size < countOfMaxProcessingTasks)
{
// get task wrapper from request queue
TaskWrapper wrapper;
+1 -1
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
+2 -8
View File
@@ -25,13 +25,7 @@
#include "network/CCDownloader.h"
// include platform specific implement class
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "network/CCDownloader-apple.h"
#include "network/CCDownloader-curl.h"
#define DownloaderImpl DownloaderCURL
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "network/CCDownloader-apple.h"
#define DownloaderImpl DownloaderApple
@@ -81,7 +75,7 @@ namespace cocos2d { namespace network {
int64_t bytesReceived,
int64_t totalBytesReceived,
int64_t totalBytesExpected,
std::function<int64_t(void *buffer, int64_t len)>& transferDataToBuffer)
std::function<int64_t(void *buffer, int64_t len)>& /*transferDataToBuffer*/)
{
if (onTaskProgress)
{
+1 -1
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
+28 -28
View File
@@ -1,18 +1,18 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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
@@ -58,7 +58,7 @@
[conn release];
[runLoop release];
[connError release];
[super dealloc];
}
@@ -67,7 +67,7 @@
#ifdef COCOS2D_DEBUG
NSLog(@"Starting to load %@", srcURL);
#endif
finish = false;
self.responseData = [NSMutableData data];
@@ -75,31 +75,31 @@
self.responseError = nil;
self.connError = nil;
// create the connection with the target request and this class as the delegate
self.conn = [[[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO] autorelease];
[self.conn scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// start the connection
[self.conn start];
}
#pragma mark NSURLConnectionDelegate methods
/**
* This delegate method is called when the NSURLConnection connects to the server. It contains the
* This delegate method is called when the NSURLConnection connects to the server. It contains the
* NSURLResponse object with the headers returned by the server. This method may be called multiple times.
* Therefore, it is important to reset the data on each call. Do not assume that it is the first call
* of this method.
**/
- (void) connection:(NSURLConnection *)connection
- (void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
#ifdef COCOS2D_DEBUG
NSLog(@"Received response from request to url %@", srcURL);
#endif
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//NSLog(@"All headers = %@", [httpResponse allHeaderFields]);
self.responseHeader = [httpResponse allHeaderFields];
@@ -108,7 +108,7 @@
self.statusString = [NSHTTPURLResponse localizedStringForStatusCode:responseCode];
if(responseCode == 200)
self.statusString = @"OK";
/*The individual values of the numeric status codes defined for HTTP/1.1
| "200" ; OK
| "201" ; Created
@@ -122,17 +122,17 @@
{// something went wrong, abort the whole thing
self.responseError = [NSError errorWithDomain:@"CCBackendDomain"
code:responseCode
userInfo:@{NSLocalizedDescriptionKey: @"Bad HTTP Response Code"}];
userInfo:@{NSLocalizedDescriptionKey: @"Bad HTTP Response Code"}];
}
[responseData setLength:0];
}
/**
* This delegate method is called for each chunk of data received from the server. The chunk size
* is dependent on the network type and the server configuration.
* is dependent on the network type and the server configuration.
*/
- (void)connection:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data
{
//NSLog(@"get some data");
@@ -141,20 +141,20 @@
}
/**
* This delegate methodis called if the connection cannot be established to the server.
* This delegate method is called if the connection cannot be established to the server.
* The error object will have a description of the error
**/
- (void)connection:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
//NSLog(@"Load failed with error %@", [error localizedDescription]);
self.connError = error;
finish = true;
}
/**
* This delegate method is called when the data load is complete. The delegate will be released
* This delegate method is called when the data load is complete. The delegate will be released
* following this call
**/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
@@ -172,16 +172,16 @@
NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
CFDataRef certDataRef = (CFDataRef)certData;
SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);
//Establish a chain of trust anchored on our bundled certificate
CFArrayRef certArrayRef = CFArrayCreate(NULL, (void*)&cert, 1, NULL);
SecTrustRef serverTrust = protectionSpace.serverTrust;
SecTrustSetAnchorCertificates(serverTrust, certArrayRef);
//Verify that trust
SecTrustResultType trustResult;
SecTrustEvaluate(serverTrust, &trustResult);
if(trustResult == kSecTrustResultRecoverableTrustFailure)
{
CFDataRef errDataRef = SecTrustCopyExceptions(serverTrust);
@@ -206,14 +206,14 @@
{
id <NSURLAuthenticationChallengeSender> sender = challenge.sender;
NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;
//Should server trust client?
if([self shouldTrustProtectionSpace:protectionSpace])
{
SecTrustRef trust = [protectionSpace serverTrust];
//
//
// SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, 0);
//
//
// NSData *serverCertificateData = (NSData*)SecCertificateCopyData(certificate);
// NSString *serverCertificateDataHash = [[serverCertificateData base64EncodedString] ]
NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
+187 -119
View File
@@ -1,20 +1,20 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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
@@ -39,18 +39,18 @@
#include "platform/android/jni/JniHelper.h"
#include "base/ccUTF8.h"
NS_CC_BEGIN
namespace network {
typedef std::vector<std::string> HttpRequestHeaders;
typedef HttpRequestHeaders::iterator HttpRequestHeadersIter;
typedef std::vector<std::string> HttpCookies;
typedef HttpCookies::iterator HttpCookiesIter;
static HttpClient* _httpClient = nullptr; // pointer to singleton
struct CookiesInfo
{
@@ -70,7 +70,7 @@ static size_t writeData(void* buffer, size_t sizes, HttpResponse* response)
recvBuffer->clear();
recvBuffer->insert(recvBuffer->end(), (char*)buffer, ((char*)buffer) + sizes);
return sizes;
}
}
//static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream)
size_t writeHeaderData(void* buffer, size_t sizes,HttpResponse* response)
@@ -85,8 +85,8 @@ class HttpURLConnection
{
public:
HttpURLConnection(HttpClient* httpClient)
:_httpURLConnection(nullptr)
,_client(httpClient)
:_client(httpClient)
,_httpURLConnection(nullptr)
,_requestmethod("")
,_responseCookies("")
,_cookieFileName("")
@@ -102,7 +102,7 @@ public:
JniHelper::getEnv()->DeleteGlobalRef(_httpURLConnection);
}
}
void setRequestMethod(const char* method)
{
_requestmethod = method;
@@ -119,8 +119,12 @@ public:
methodInfo.env->DeleteLocalRef(jstr);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
bool init(HttpRequest* request)
{
createHttpURLConnection(request->getUrl());
@@ -133,27 +137,25 @@ public:
if(!headers.empty())
{
/* append custom headers one by one */
for (HttpRequestHeadersIter it = headers.begin(); it != headers.end(); ++it)
for (auto& header : headers)
{
std::string val = *it;
int len = val.length();
int pos = val.find(':');
int len = header.length();
int pos = header.find(':');
if (-1 == pos || pos >= len)
{
continue;
}
std::string str1 = val.substr(0, pos);
std::string str2 = val.substr(pos + 1, len - pos - 1);
std::string str1 = header.substr(0, pos);
std::string str2 = header.substr(pos + 1, len - pos - 1);
addRequestHeader(str1.c_str(), str2.c_str());
}
}
addCookiesForRequestHeader();
return true;
}
int connect()
{
int suc = 0;
@@ -167,10 +169,14 @@ public:
methodInfo.classID, methodInfo.methodID, _httpURLConnection);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return suc;
}
void disconnect()
{
JniMethodInfo methodInfo;
@@ -183,8 +189,12 @@ public:
methodInfo.classID, methodInfo.methodID, _httpURLConnection);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
int getResponseCode()
{
int responseCode = 0;
@@ -198,10 +208,14 @@ public:
methodInfo.classID, methodInfo.methodID, _httpURLConnection);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return responseCode;
}
char* getResponseMessage()
{
char* message = nullptr;
@@ -220,10 +234,14 @@ public:
}
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return message;
}
void sendRequest(HttpRequest* request)
{
JniMethodInfo methodInfo;
@@ -232,7 +250,7 @@ public:
"sendRequest",
"(Ljava/net/HttpURLConnection;[B)V"))
{
jbyteArray bytearray;
ssize_t dataSize = request->getRequestDataSize();
bytearray = methodInfo.env->NewByteArray(dataSize);
@@ -242,34 +260,38 @@ public:
methodInfo.env->DeleteLocalRef(bytearray);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
size_t saveResponseCookies(const char* responseCookies, size_t count)
{
if (nullptr == responseCookies || strlen(responseCookies) == 0 || count == 0)
{
return 0;
}
if (_cookieFileName.empty())
{
_cookieFileName = FileUtils::getInstance()->getWritablePath() + "cookieFile.txt";
}
FILE* fp = fopen(_cookieFileName.c_str(), "w");
if (nullptr == fp)
{
CCLOG("can't create or open response cookie files");
return 0;
}
fwrite(responseCookies, sizeof(char), count, fp);
fclose(fp);
return count;
}
char* getResponseHeaders()
{
char* headers = nullptr;
@@ -287,18 +309,22 @@ public:
}
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return headers;
}
char* getResponseContent(HttpResponse* response)
{
if (nullptr == response)
{
return nullptr;
}
char* content = nullptr;
JniMethodInfo methodInfo;
if (JniHelper::getStaticMethodInfo(methodInfo,
@@ -308,18 +334,22 @@ public:
{
jobject jObj = methodInfo.env->CallStaticObjectMethod(
methodInfo.classID, methodInfo.methodID, _httpURLConnection);
_contentLength = getCStrFromJByteArray((jbyteArray)jObj, methodInfo.env, &content);
if (nullptr != jObj)
if (nullptr != jObj)
{
methodInfo.env->DeleteLocalRef(jObj);
}
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return content;
}
char* getResponseHeaderByKey(const char* key)
{
char* value = nullptr;
@@ -339,10 +369,14 @@ public:
}
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return value;
}
int getResponseHeaderByKeyInt(const char* key)
{
int contentLength = 0;
@@ -358,10 +392,14 @@ public:
methodInfo.env->DeleteLocalRef(jstrKey);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return contentLength;
}
char* getResponseHeaderByIdx(int idx)
{
char* header = nullptr;
@@ -379,25 +417,29 @@ public:
}
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
return header;
}
const std::string& getCookieFileName() const
{
return _cookieFileName;
}
void setCookieFileName(std::string& filename)
{
_cookieFileName = filename;
}
int getContentLength()
{
return _contentLength;
}
private:
void createHttpURLConnection(const std::string& url)
{
@@ -415,9 +457,13 @@ private:
methodInfo.env->DeleteLocalRef(jObj);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
void addRequestHeader(const char* key, const char* value)
void addRequestHeader(const char* key, const char* value)
{
JniMethodInfo methodInfo;
if (JniHelper::getStaticMethodInfo(methodInfo,
@@ -433,61 +479,62 @@ private:
methodInfo.env->DeleteLocalRef(jstrVal);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
void addCookiesForRequestHeader()
{
if(_client->getCookieFilename().empty())
{
return;
}
_cookieFileName = FileUtils::getInstance()->fullPathForFilename(_client->getCookieFilename());
std::string cookiesInfo = FileUtils::getInstance()->getStringFromFile(_cookieFileName);
if (cookiesInfo.empty())
return;
HttpCookies cookiesVec;
cookiesVec.clear();
std::stringstream stream(cookiesInfo);
std::string item;
while (std::getline(stream, item, '\n'))
{
cookiesVec.push_back(item);
}
if (cookiesVec.empty())
return;
HttpCookiesIter iter = cookiesVec.begin();
std::vector<CookiesInfo> cookiesInfoVec;
cookiesInfoVec.clear();
for (; iter != cookiesVec.end(); iter++)
for (auto& cookies : cookiesVec)
{
std::string cookies = *iter;
if (cookies.find("#HttpOnly_") != std::string::npos)
{
cookies = cookies.substr(10);
}
if(cookies.at(0) == '#')
continue;
CookiesInfo co;
std::stringstream streamInfo(cookies);
std::string item;
std::vector<std::string> elems;
while (std::getline(streamInfo, item, '\t'))
{
elems.push_back(item);
}
co.domain = elems[0];
if (co.domain.at(0) == '.')
{
@@ -502,19 +549,18 @@ private:
cookiesInfoVec.push_back(co);
}
std::vector<CookiesInfo>::iterator cookiesIter = cookiesInfoVec.begin();
std::string sendCookiesInfo = "";
int cookiesCount = 0;
for (; cookiesIter != cookiesInfoVec.end(); cookiesIter++)
for (auto& cookieInfo : cookiesInfoVec)
{
if (_url.find(cookiesIter->domain) != std::string::npos)
if (_url.find(cookieInfo.domain) != std::string::npos)
{
std::string keyValue = cookiesIter->key;
std::string keyValue = cookieInfo.key;
keyValue.append("=");
keyValue.append(cookiesIter->value);
keyValue.append(cookieInfo.value);
if (cookiesCount != 0)
sendCookiesInfo.append(";");
sendCookiesInfo.append(keyValue);
}
cookiesCount++;
@@ -536,6 +582,10 @@ private:
methodInfo.classID, methodInfo.methodID, _httpURLConnection, readMiliseconds, connectMiliseconds);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
void setVerifySSL()
@@ -557,10 +607,14 @@ private:
methodInfo.env->DeleteLocalRef(jstrfullpath);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
else
{
CCLOGERROR("HttpClient::%s failed!", __FUNCTION__);
}
}
bool configure()
{
{
if(nullptr == _httpURLConnection)
{
return false;
@@ -584,10 +638,8 @@ private:
{
return nullptr;
}
char *ret = nullptr;
std::string strValue = cocos2d::StringUtils::getStringUTFCharsJNI(env, jstr);
ret = strdup(strValue.c_str());
return ret;
return strdup(strValue.c_str());
}
int getCStrFromJByteArray(jbyteArray jba, JNIEnv* env, char** ppData)
@@ -598,10 +650,8 @@ private:
return 0;
}
char* str = nullptr;
int len = env->GetArrayLength(jba);
str = (char*)malloc(sizeof(char)*len);
int len = env->GetArrayLength(jba);
char* str = (char*)malloc(sizeof(char)*len);
env->GetByteArrayRegion(jba, 0, len, (jbyte*)str);
*ppData = str;
@@ -686,6 +736,14 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
responseCode = urlConnection.getResponseCode();
if (0 == responseCode)
{
response->setSucceed(false);
response->setErrorBuffer("connect failed");
response->setResponseCode(-1);
return;
}
char* headers = urlConnection.getResponseHeaders();
if (nullptr != headers)
{
@@ -704,17 +762,20 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
//content len
int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length");
char* contentInfo = urlConnection.getResponseContent(response);
if (nullptr != contentInfo)
if (nullptr != contentInfo)
{
std::vector<char> * recvBuffer = (std::vector<char>*)response->getResponseData();
recvBuffer->clear();
recvBuffer->insert(recvBuffer->begin(), (char*)contentInfo, ((char*)contentInfo) + urlConnection.getContentLength());
}
free(contentInfo);
char *messageInfo = urlConnection.getResponseMessage();
strcpy(responseMessage, messageInfo);
free(messageInfo);
if (messageInfo)
{
strcpy(responseMessage, messageInfo);
free(messageInfo);
}
urlConnection.disconnect();
@@ -724,7 +785,14 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
if (responseCode == -1)
{
response->setSucceed(false);
response->setErrorBuffer(responseMessage);
if (responseMessage != nullptr)
{
response->setErrorBuffer(responseMessage);
}
else
{
response->setErrorBuffer("response code error!");
}
}
else
{
@@ -734,10 +802,10 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
// Worker thread
void HttpClient::networkThread()
{
{
increaseThreadCount();
while (true)
while (true)
{
HttpRequest *request;
@@ -754,16 +822,16 @@ void HttpClient::networkThread()
if (request == _requestSentinel) {
break;
}
// Create a HttpResponse object, the default setting is http access failed
HttpResponse *response = new (std::nothrow) HttpResponse(request);
processResponse(response, _responseMessage);
// add response packet into queue
_responseQueueMutex.lock();
_responseQueue.pushBack(response);
_responseQueueMutex.unlock();
_schedulerMutex.lock();
if (nullptr != _scheduler)
{
@@ -771,17 +839,17 @@ void HttpClient::networkThread()
}
_schedulerMutex.unlock();
}
// cleanup: if worker thread received quit signal, clean up un-completed request queue
_requestQueueMutex.lock();
_requestQueue.clear();
_requestQueueMutex.unlock();
_responseQueueMutex.lock();
_responseQueue.clear();
_responseQueueMutex.unlock();
decreaseThreadCountAndMayDeleteThis();
decreaseThreadCountAndMayDeleteThis();
}
// Worker thread
@@ -815,11 +883,11 @@ void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response
// HttpClient implementation
HttpClient* HttpClient::getInstance()
{
if (_httpClient == nullptr)
if (_httpClient == nullptr)
{
_httpClient = new (std::nothrow) HttpClient();
}
return _httpClient;
}
@@ -852,7 +920,7 @@ void HttpClient::destroyInstance()
CCLOG("HttpClient::destroyInstance() finished!");
}
void HttpClient::enableCookies(const char* cookieFile)
void HttpClient::enableCookies(const char* cookieFile)
{
std::lock_guard<std::mutex> lock(_cookieFileMutex);
if (cookieFile)
@@ -864,7 +932,7 @@ void HttpClient::enableCookies(const char* cookieFile)
_cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
}
}
void HttpClient::setSSLVerification(const std::string& caFile)
{
std::lock_guard<std::mutex> lock(_sslCaFileMutex);
@@ -872,12 +940,12 @@ void HttpClient::setSSLVerification(const std::string& caFile)
}
HttpClient::HttpClient()
: _timeoutForConnect(30)
: _isInited(false)
, _timeoutForConnect(30)
, _timeoutForRead(60)
, _isInited(false)
, _threadCount(0)
, _requestSentinel(new HttpRequest())
, _cookie(nullptr)
, _requestSentinel(new HttpRequest())
{
CCLOG("In the constructor of HttpClient!");
increaseThreadCount();
@@ -891,7 +959,7 @@ HttpClient::~HttpClient()
}
//Lazy create semaphore & mutex & thread
bool HttpClient::lazyInitThreadSemphore()
bool HttpClient::lazyInitThreadSemaphore()
{
if (_isInited)
{
@@ -909,17 +977,17 @@ bool HttpClient::lazyInitThreadSemphore()
//Add a get task to queue
void HttpClient::send(HttpRequest* request)
{
if (!lazyInitThreadSemphore())
{
if (!lazyInitThreadSemaphore())
{
return;
}
if (nullptr == request)
{
return;
}
request->retain();
_requestQueueMutex.lock();
@@ -951,7 +1019,7 @@ void HttpClient::dispatchResponseCallbacks()
// log("CCHttpClient::dispatchResponseCallbacks is running");
//occurs when cocos thread fires but the network thread has already quited
HttpResponse* response = nullptr;
_responseQueueMutex.lock();
if (!_responseQueue.empty())
@@ -961,7 +1029,7 @@ void HttpClient::dispatchResponseCallbacks()
}
_responseQueueMutex.unlock();
if (response)
{
HttpRequest *request = response->getHttpRequest();
@@ -994,7 +1062,7 @@ void HttpClient::decreaseThreadCountAndMayDeleteThis()
{
needDeleteThis = true;
}
_threadCountMutex.unlock();
if (needDeleteThis)
{
@@ -1007,31 +1075,31 @@ void HttpClient::setTimeoutForConnect(int value)
std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
_timeoutForConnect = value;
}
int HttpClient::getTimeoutForConnect()
{
std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
return _timeoutForConnect;
}
void HttpClient::setTimeoutForRead(int value)
{
std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
_timeoutForRead = value;
}
int HttpClient::getTimeoutForRead()
{
std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
return _timeoutForRead;
}
const std::string& HttpClient::getCookieFilename()
{
std::lock_guard<std::mutex> lock(_cookieFileMutex);
return _cookieFilename;
}
const std::string& HttpClient::getSSLVerification()
{
std::lock_guard<std::mutex> lock(_sslCaFileMutex);
+32 -31
View File
@@ -1,7 +1,7 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -49,8 +49,9 @@ static int processTask(HttpClient* client, HttpRequest *request, NSString *reque
void HttpClient::networkThread()
{
increaseThreadCount();
while (true) @autoreleasepool {
HttpRequest *request;
// step 1: send http request if the requestQueue isn't empty
@@ -84,16 +85,16 @@ void HttpClient::networkThread()
}
_schedulerMutex.unlock();
}
// cleanup: if worker thread received quit signal, clean up un-completed request queue
_requestQueueMutex.lock();
_requestQueue.clear();
_requestQueueMutex.unlock();
_responseQueueMutex.lock();
_responseQueue.clear();
_responseQueueMutex.unlock();
decreaseThreadCountAndMayDeleteThis();
}
@@ -101,7 +102,7 @@ void HttpClient::networkThread()
void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response)
{
increaseThreadCount();
char responseMessage[RESPONSE_BUFFER_SIZE] = { 0 };
processResponse(response, responseMessage);
@@ -133,7 +134,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
strcpy(errorBuffer, "client object is invalid");
return 0;
}
//create request with url
NSString* urlstring = [NSString stringWithUTF8String:request->getUrl()];
NSURL *url = [NSURL URLWithString:urlstring];
@@ -150,12 +151,12 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
if(!headers.empty())
{
/* append custom headers one by one */
for (std::vector<std::string>::iterator it = headers.begin(); it != headers.end(); ++it)
for (auto& header : headers)
{
unsigned long i = it->find(':', 0);
unsigned long length = it->size();
std::string field = it->substr(0, i);
std::string value = it->substr(i+1, length-i);
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);
NSString *headerField = [NSString stringWithUTF8String:field.c_str()];
NSString *headerValue = [NSString stringWithUTF8String:value.c_str()];
[nsrequest setValue:headerValue forHTTPHeaderField:headerField];
@@ -164,7 +165,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
//if request type is post or put,set header and data
if([requestType isEqual: @"POST"] || [requestType isEqual: @"PUT"])
{
{
char* requestDataBuffer = request->getRequestData();
if (nullptr != requestDataBuffer && 0 != request->getRequestDataSize())
{
@@ -190,34 +191,34 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
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];
}
}
HttpAsynConnection *httpAsynConn = [[HttpAsynConnection new] autorelease];
httpAsynConn.srcURL = urlstring;
httpAsynConn.sslFile = nil;
std::string sslCaFileName = client->getSSLVerification();
if(!sslCaFileName.empty())
{
long len = sslCaFileName.length();
long pos = sslCaFileName.rfind('.', len-1);
httpAsynConn.sslFile = [NSString stringWithUTF8String:sslCaFileName.substr(0, pos).c_str()];
}
[httpAsynConn startRequest:nsrequest];
while( httpAsynConn.finish != true)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
//if http connection return error
if (httpAsynConn.connError != nil)
{
@@ -232,9 +233,9 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
NSString* errorString = [httpAsynConn.responseError localizedDescription];
strcpy(errorBuffer, [errorString UTF8String]);
}
*responseCode = httpAsynConn.responseCode;
//add cookie to cookies vector
if(!cookieFilename.empty())
{
@@ -249,7 +250,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
NSDate *date = cookie.expiresDate;
NSString *name = cookie.name;
NSString *value = cookie.value;
CookiesInfo cookieInfo;
cookieInfo.domain = [domain cStringUsingEncoding: NSUTF8StringEncoding];
cookieInfo.path = [path cStringUsingEncoding: NSUTF8StringEncoding];
@@ -258,11 +259,11 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
cookieInfo.name = [name cStringUsingEncoding: NSUTF8StringEncoding];
cookieInfo.value = [value cStringUsingEncoding: NSUTF8StringEncoding];
cookieInfo.tailmatch = true;
client->getCookie()->updateOrAddCookie(&cookieInfo);
}
}
//handle response header
NSMutableString *header = [NSMutableString string];
[header appendFormat:@"HTTP/1.1 %ld %@\n", (long)httpAsynConn.responseCode, httpAsynConn.statusString];
@@ -358,12 +359,12 @@ void HttpClient::setSSLVerification(const std::string& caFile)
}
HttpClient::HttpClient()
: _timeoutForConnect(30)
: _isInited(false)
, _timeoutForConnect(30)
, _timeoutForRead(60)
, _isInited(false)
, _threadCount(0)
, _requestSentinel(new HttpRequest())
, _cookie(nullptr)
, _requestSentinel(new HttpRequest())
{
CCLOG("In the constructor of HttpClient!");
memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE);
@@ -384,7 +385,7 @@ HttpClient::~HttpClient()
}
//Lazy create semaphore & mutex & thread
bool HttpClient::lazyInitThreadSemphore()
bool HttpClient::lazyInitThreadSemaphore()
{
if (_isInited)
{
@@ -403,7 +404,7 @@ bool HttpClient::lazyInitThreadSemphore()
//Add a get task to queue
void HttpClient::send(HttpRequest* request)
{
if (false == lazyInitThreadSemphore())
if (false == lazyInitThreadSemaphore())
{
return;
}
@@ -496,7 +497,7 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
break;
default:
CCASSERT(false , "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported");
CCASSERT(false, "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported");
break;
}
+36 -35
View File
@@ -1,20 +1,20 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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
@@ -48,11 +48,11 @@ static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream)
{
std::vector<char> *recvBuffer = (std::vector<char>*)stream;
size_t sizes = size * nmemb;
// add data to the end of recvBuffer
// write data maybe called more than once in a single request
recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes);
return sizes;
}
@@ -61,11 +61,11 @@ static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream
{
std::vector<char> *recvBuffer = (std::vector<char>*)stream;
size_t sizes = size * nmemb;
// add data to the end of recvBuffer
// write data maybe called more than once in a single request
recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes);
return sizes;
}
@@ -101,7 +101,7 @@ void HttpClient::networkThread()
}
// step 2: libcurl sync access
// Create a HttpResponse object, the default setting is http access failed
HttpResponse *response = new (std::nothrow) HttpResponse(request);
@@ -120,7 +120,7 @@ void HttpClient::networkThread()
}
_schedulerMutex.unlock();
}
// cleanup: if worker thread received quit signal, clean up un-completed request queue
_requestQueueMutex.lock();
_requestQueue.clear();
@@ -167,7 +167,7 @@ static bool configureCURL(HttpClient* client, CURL* handle, char* errorBuffer)
if (!handle) {
return false;
}
int32_t code;
code = curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, errorBuffer);
if (code != CURLE_OK) {
@@ -191,9 +191,9 @@ static bool configureCURL(HttpClient* client, CURL* handle, char* errorBuffer)
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(handle, CURLOPT_CAINFO, sslCaFilename.c_str());
}
// FIXED #3224: The subthread of CCHttpClient interrupts main thread if timeout comes.
// Document is here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTNOSIGNAL
// Document is here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTNOSIGNAL
curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, "");
@@ -247,8 +247,8 @@ public:
if(!headers.empty())
{
/* append custom headers one by one */
for (std::vector<std::string>::iterator it = headers.begin(); it != headers.end(); ++it)
_headers = curl_slist_append(_headers,it->c_str());
for (auto& header : headers)
_headers = curl_slist_append(_headers,header.c_str());
/* set custom headers for curl */
if (!setOption(CURLOPT_HTTPHEADER, _headers))
return false;
@@ -268,7 +268,7 @@ public:
&& setOption(CURLOPT_WRITEDATA, stream)
&& setOption(CURLOPT_HEADERFUNCTION, headerCallback)
&& setOption(CURLOPT_HEADERDATA, headerStream);
}
/// @param responseCode Null not allowed
@@ -282,7 +282,7 @@ public:
return false;
}
// Get some mor data.
return true;
}
};
@@ -339,7 +339,7 @@ HttpClient* HttpClient::getInstance()
{
_httpClient = new (std::nothrow) HttpClient();
}
return _httpClient;
}
@@ -382,7 +382,7 @@ void HttpClient::enableCookies(const char* cookieFile)
_cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
}
}
void HttpClient::setSSLVerification(const std::string& caFile)
{
std::lock_guard<std::mutex> lock(_sslCaFileMutex);
@@ -390,12 +390,12 @@ void HttpClient::setSSLVerification(const std::string& caFile)
}
HttpClient::HttpClient()
: _timeoutForConnect(30)
: _isInited(false)
, _timeoutForConnect(30)
, _timeoutForRead(60)
, _isInited(false)
, _threadCount(0)
, _requestSentinel(new HttpRequest())
, _cookie(nullptr)
, _requestSentinel(new HttpRequest())
{
CCLOG("In the constructor of HttpClient!");
memset(_responseMessage, 0, RESPONSE_BUFFER_SIZE * sizeof(char));
@@ -410,7 +410,7 @@ HttpClient::~HttpClient()
}
//Lazy create semaphore & mutex & thread
bool HttpClient::lazyInitThreadSemphore()
bool HttpClient::lazyInitThreadSemaphore()
{
if (_isInited)
{
@@ -422,23 +422,23 @@ bool HttpClient::lazyInitThreadSemphore()
t.detach();
_isInited = true;
}
return true;
}
//Add a get task to queue
void HttpClient::send(HttpRequest* request)
{
if (false == lazyInitThreadSemphore())
if (false == lazyInitThreadSemaphore())
{
return;
}
if (!request)
{
return;
}
request->retain();
_requestQueueMutex.lock();
@@ -478,7 +478,7 @@ void HttpClient::dispatchResponseCallbacks()
_responseQueue.erase(0);
}
_responseQueueMutex.unlock();
if (response)
{
HttpRequest *request = response->getHttpRequest();
@@ -546,7 +546,7 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
break;
default:
CCASSERT(false , "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported");
CCASSERT(false, "CCHttpClient: unknown request type, only GET, POST, PUT or DELETE is supported");
break;
}
@@ -592,31 +592,31 @@ void HttpClient::setTimeoutForConnect(int value)
std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
_timeoutForConnect = value;
}
int HttpClient::getTimeoutForConnect()
{
std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
return _timeoutForConnect;
}
void HttpClient::setTimeoutForRead(int value)
{
std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
_timeoutForRead = value;
}
int HttpClient::getTimeoutForRead()
{
std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
return _timeoutForRead;
}
const std::string& HttpClient::getCookieFilename()
{
std::lock_guard<std::mutex> lock(_cookieFileMutex);
return _cookieFilename;
}
const std::string& HttpClient::getSSLVerification()
{
std::lock_guard<std::mutex> lock(_sslCaFileMutex);
@@ -627,3 +627,4 @@ const std::string& HttpClient::getSSLVerification()
NS_CC_END
+2 -2
View File
@@ -1,7 +1,7 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -162,7 +162,7 @@ private:
* Init pthread mutex, semaphore, and create new thread for http requests
* @return bool
*/
bool lazyInitThreadSemphore();
bool lazyInitThreadSemaphore();
void networkThread();
void networkThreadAlone(HttpRequest* request, HttpResponse* response);
/** Poll function called from main thread to dispatch callbacks when http requests finished **/
+16 -18
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -47,10 +47,8 @@ void HttpCookie::readFile()
_cookies.clear();
for(auto iter = cookiesVec.begin();iter != cookiesVec.end(); iter++)
for(auto& cookie : cookiesVec)
{
std::string cookie = *iter;
if(cookie.length() == 0)
continue;
@@ -95,10 +93,10 @@ const std::vector<CookiesInfo>* HttpCookie::getCookies() const
const CookiesInfo* HttpCookie::getMatchCookie(const std::string& url) const
{
for(auto iter = _cookies.begin(); iter != _cookies.end(); iter++)
for(auto& cookie : _cookies)
{
if(url.find(iter->domain) != std::string::npos)
return &(*iter);
if(url.find(cookie.domain) != std::string::npos)
return &cookie;
}
return nullptr;
@@ -106,11 +104,11 @@ const CookiesInfo* HttpCookie::getMatchCookie(const std::string& url) const
void HttpCookie::updateOrAddCookie(CookiesInfo* cookie)
{
for(auto iter = _cookies.begin(); iter != _cookies.end(); iter++)
for(auto& _cookie : _cookies)
{
if(cookie->domain == iter->domain)
if(cookie->domain == _cookie.domain)
{
*iter = *cookie;
_cookie = *cookie;
return;
}
}
@@ -128,22 +126,22 @@ void HttpCookie::writeFile()
out);
std::string line;
for(auto iter = _cookies.begin(); iter != _cookies.end(); iter++)
for(auto& cookie : _cookies)
{
line.clear();
line.append(iter->domain);
line.append(cookie.domain);
line.append(1, '\t');
iter->tailmatch ? line.append("TRUE") : line.append("FALSE");
cookie.tailmatch ? line.append("TRUE") : line.append("FALSE");
line.append(1, '\t');
line.append(iter->path);
line.append(cookie.path);
line.append(1, '\t');
iter->secure ? line.append("TRUE") : line.append("FALSE");
cookie.secure ? line.append("TRUE") : line.append("FALSE");
line.append(1, '\t');
line.append(iter->expires);
line.append(cookie.expires);
line.append(1, '\t');
line.append(iter->name);
line.append(cookie.name);
line.append(1, '\t');
line.append(iter->value);
line.append(cookie.value);
//line.append(1, '\n');
fprintf(out, "%s\n", line.c_str());
+1 -1
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
+2 -2
View File
@@ -1,6 +1,6 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -79,7 +79,7 @@ public:
/**
* Constructor.
* Because HttpRequest object will be used between UI thead and network thread,
* Because HttpRequest object will be used between UI thread and network thread,
requestObj->autorelease() is forbidden to avoid crashes in AutoreleasePool
new/retain/release still works, which means you need to release it manually
Please refer to HttpRequestTest.cpp to find its usage.
+7 -6
View File
@@ -1,6 +1,6 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -51,9 +51,9 @@ public:
* @param request the corresponding HttpRequest which leads to this response.
*/
HttpResponse(HttpRequest* request)
: _pHttpRequest(request)
, _succeed(false)
, _responseDataString("")
: _pHttpRequest(request)
, _succeed(false)
, _responseDataString("")
{
if (_pHttpRequest)
{
@@ -89,7 +89,7 @@ public:
/**
* Get the corresponding HttpRequest object which leads to this response.
* There's no paired setter for it, because it's already setted in class constructor
* There's no paired setter for it, because it's already set in class constructor
* @return HttpRequest* the corresponding HttpRequest object which leads to this response.
*/
inline HttpRequest* getHttpRequest() const
@@ -196,7 +196,8 @@ public:
inline void setErrorBuffer(const char* value)
{
_errorBuffer.clear();
_errorBuffer.assign(value);
if (value != nullptr)
_errorBuffer.assign(value);
}
/**
@@ -234,7 +234,6 @@ public class Cocos2dxEditBoxHelper {
if (editBox != null) {
mEditBoxArray.remove(index);
mFrameLayout.removeView(editBox);
Log.e(TAG, "remove EditBox");
}
}
});
@@ -150,6 +150,9 @@ public class Cocos2dxHttpURLConnection
Log.e("cocos2d-x debug info", "come in connect");
Log.e("cocos2d-x debug info", e.toString());
suc = 1;
} catch (Exception e) {
e.printStackTrace();
suc = 1;
}
return suc;
@@ -101,6 +101,8 @@ public class Cocos2dxWebViewHelper {
if (webView != null) {
webViews.remove(index);
sLayout.removeView(webView);
webView.destroy();
webView = null;
}
}
});
@@ -145,7 +145,6 @@ let BreakpointActor = ActorClassWithSpec(breakpointSpec, {
* The stack frame that contained the breakpoint.
*/
hit: function (frame) {
log('....');
// Don't pause if we are currently stepping (in or over) or the frame is
// black-boxed.
let generatedLocation = this.threadActor.sources.getFrameLocation(frame);
@@ -185,7 +185,6 @@ TabSources.prototype = {
let sourceActorStore = this._thread.sourceActorStore;
var id = sourceActorStore.getReusableActorId(source, originalUrl);
if (id) {
log("++++ source " + originalUrl + ": " + id);
actor.actorID = id;
}
@@ -1645,7 +1645,6 @@ DebuggerServerConnection.prototype = {
this.currentPacket = undefined;
}
} else {
log("...." + actor._originalUrl + ", " + actor.requestTypes);
ret = { error: "unrecognizedPacketType",
message: ("Actor " + actor.actorID +
" does not recognize the packet type " +
+7 -1
View File
@@ -156,7 +156,13 @@ namespace experimental{
Widget::onExit();
_impl->setVisible(false);
}
void WebView::cleanup()
{
ProtectedNode::cleanup();
_impl->loadURL("about:blank");
}
void WebView::setBounces(bool bounces)
{
_impl->setBounces(bounces);
+1
View File
@@ -211,6 +211,7 @@ public:
virtual void setVisible(bool visible) override;
virtual void onEnter() override;
virtual void onExit() override;
virtual void cleanup() override;
protected:
virtual cocos2d::ui::Widget* createCloneInstance() override;
@@ -132,12 +132,12 @@ def copySo() {
}
afterEvaluate {
externalNativeBuildDebug.doLast {
tasks.findByName('externalNativeBuildDebug')?.doLast {
println ('Copying debug .so')
copySo()
}
externalNativeBuildRelease.doLast {
tasks.findByName('externalNativeBuildRelease')?.doLast {
println ('Copying release .so')
copySo()
}
@@ -132,12 +132,12 @@ def copySo() {
}
afterEvaluate {
externalNativeBuildDebug.doLast {
tasks.findByName('externalNativeBuildDebug')?.doLast {
println ('Copying debug .so')
copySo()
}
externalNativeBuildRelease.doLast {
tasks.findByName('externalNativeBuildRelease')?.doLast {
println ('Copying release .so')
copySo()
}
@@ -132,12 +132,12 @@ def copySo() {
}
afterEvaluate {
externalNativeBuildDebug.doLast {
tasks.findByName('externalNativeBuildDebug')?.doLast {
println ('Copying debug .so')
copySo()
}
externalNativeBuildRelease.doLast {
tasks.findByName('externalNativeBuildRelease')?.doLast {
println ('Copying release .so')
copySo()
}