From 4147b27e3bfe8d0dc0ca97cb3f8bf13ea93aa0ed Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 29 Aug 2017 17:19:28 +0800 Subject: [PATCH 01/10] fix WebView bug for fireball/issues/6328 --- .../java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java | 2 ++ native/cocos/ui/UIWebView-inl.h | 8 +++++++- native/cocos/ui/UIWebView.h | 1 + 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java index 012d4b62bb..d18e4e88f4 100755 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java @@ -101,6 +101,8 @@ public class Cocos2dxWebViewHelper { if (webView != null) { webViews.remove(index); sLayout.removeView(webView); + webView.destroy(); + webView = null; } } }); diff --git a/native/cocos/ui/UIWebView-inl.h b/native/cocos/ui/UIWebView-inl.h index 0557d09a20..586922f4de 100644 --- a/native/cocos/ui/UIWebView-inl.h +++ b/native/cocos/ui/UIWebView-inl.h @@ -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); diff --git a/native/cocos/ui/UIWebView.h b/native/cocos/ui/UIWebView.h index 1b879521b0..c2fe51b702 100644 --- a/native/cocos/ui/UIWebView.h +++ b/native/cocos/ui/UIWebView.h @@ -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; From 9ebcbe0d53ee61405583b125aae6ad08803e8893 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 29 Aug 2017 17:39:24 +0800 Subject: [PATCH 02/10] Refactor ScriptingCore::removeObjectProxy --- native/cocos/base/CCScriptSupport.h | 2 +- native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp | 2 +- native/cocos/scripting/js-bindings/manual/ScriptingCore.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/native/cocos/base/CCScriptSupport.h b/native/cocos/base/CCScriptSupport.h index 4efa284d3b..919669e168 100644 --- a/native/cocos/base/CCScriptSupport.h +++ b/native/cocos/base/CCScriptSupport.h @@ -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() {} diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 72edc76775..a25423ad44 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -1916,7 +1916,7 @@ void ScriptingCore::unrootObject(Ref* ref) else CCLOG("unrootObject: BUG. native not found: %p (%s)", ref, typeid(*ref).name()); } -void ScriptingCore::removeObjectProxy(Ref* obj) +void ScriptingCore::removeObjectProxy(void* obj) { auto proxy = jsb_get_native_proxy(obj); if (proxy) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h index 7a71cdc0f4..de4098eb4f 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h @@ -496,7 +496,7 @@ public: /** Remove proxy for a native object */ - virtual void removeObjectProxy(cocos2d::Ref* obj) override; + virtual void removeObjectProxy(void* obj) override; /** * Calls the Garbage Collector From b9dae71cce126bddfdc10b9a3a33487803861edb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 29 Aug 2017 17:41:02 +0800 Subject: [PATCH 03/10] Complete jsb proxy tracking log infos --- .../cocos/scripting/js-bindings/manual/ScriptingCore.cpp | 4 ++++ .../scripting/js-bindings/manual/cocos2d_specifics.hpp | 9 ++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index a25423ad44..3ffcd9e767 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -2256,6 +2256,10 @@ void jsb_ref_autoreleased_init(JSContext* cx, JS::HandleObject obj, Ref* ref, co // rebind void jsb_ref_rebind(JSContext* cx, JS::HandleObject jsobj, js_proxy_t *proxy, cocos2d::Ref* oldRef, cocos2d::Ref* newRef, const char* debug) { +#if COCOS2D_DEBUG > 1 + CCLOG("------REBOUND------ Cpp(%s): %p - JS: %p", debug, oldRef, jsobj.get()); + CCLOG("++++++REBOUND++++++ Cpp(%s): %p - JS: %p", debug, newRef, jsobj.get()); +#endif // COCOS2D_DEBUG #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS // Release the old reference as it have been retained by jsobj previously, // and the jsobj won't have any chance to release it in the future diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp index a410d90428..6391e9b467 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp @@ -76,11 +76,11 @@ namespace jsb } ~Object() { -#if COCOS2D_DEBUG > 1 - CCLOG("Release JSBObject %p, with proxy: %p", this, _proxy); -#endif // COCOS2D_DEBUG if (_proxy) { +#if COCOS2D_DEBUG > 1 + CCLOG("Release JSBObject %p, with proxy: %p", this, _proxy); +#endif // COCOS2D_DEBUG jsb_remove_proxy(_proxy); } } @@ -88,6 +88,9 @@ namespace jsb { if (_proxy) { +#if COCOS2D_DEBUG > 1 + CCLOG("Release JSBObject %p, with proxy: %p", this, _proxy); +#endif // COCOS2D_DEBUG jsb_remove_proxy(_proxy); } JS::RootedValue val(cx, JS::ObjectOrNullValue(jsobj)); From a4728843890d54b496d638bf014d13602c114b55 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 29 Aug 2017 17:50:38 +0800 Subject: [PATCH 04/10] Fix crash caused by physics proxy management --- .../manual/box2d/js_bindings_box2d_manual.cpp | 20 ++++--------------- .../creator/js_bindings_creator_manual.cpp | 5 +---- 2 files changed, 5 insertions(+), 20 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/box2d/js_bindings_box2d_manual.cpp b/native/cocos/scripting/js-bindings/manual/box2d/js_bindings_box2d_manual.cpp index bbff4ac0c2..28c41ed2ac 100644 --- a/native/cocos/scripting/js-bindings/manual/box2d/js_bindings_box2d_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/box2d/js_bindings_box2d_manual.cpp @@ -916,10 +916,7 @@ bool js_box2dclasses_b2World_CreateJoint(JSContext *cx, uint32_t argc, JS::Value JS::RootedValue jsret(cx); if (ret) { // box2d will reuse cached memory, need first remove old proxy when create new jsobject - auto retProxy = jsb_get_native_proxy(ret); - if (retProxy) { - jsb_remove_proxy(retProxy); - } + ScriptingCore::getInstance()->removeObjectProxy(ret); JS::RootedObject retObj(cx); js_get_or_create_jsobject(cx, (b2Joint*)ret, &retObj); jsret = JS::ObjectOrNullValue(retObj); @@ -947,10 +944,7 @@ bool js_box2dclasses_b2World_CreateBody(JSContext *cx, uint32_t argc, JS::Value JS::RootedValue jsret(cx); if (ret) { // box2d will reuse cached memory, need first remove old proxy when create new jsobject - auto retProxy = jsb_get_native_proxy(ret); - if (retProxy) { - jsb_remove_proxy(retProxy); - } + ScriptingCore::getInstance()->removeObjectProxy(ret); JS::RootedObject retObj(cx); js_get_or_create_jsobject(cx, (b2Body*)ret, &retObj); jsret = JS::ObjectOrNullValue(retObj); @@ -994,10 +988,7 @@ bool js_box2dclasses_b2Body_CreateFixture(JSContext *cx, uint32_t argc, JS::Valu JS::RootedValue jsret(cx); if (ret) { // box2d will reuse cached memory, need first remove old proxy when create new jsobject - auto retProxy = jsb_get_native_proxy(ret); - if (retProxy) { - jsb_remove_proxy(retProxy); - } + ScriptingCore::getInstance()->removeObjectProxy(ret); JS::RootedObject retObj(cx); js_get_or_create_jsobject(cx, (b2Fixture*)ret, &retObj); jsret = JS::ObjectOrNullValue(retObj); @@ -1017,10 +1008,7 @@ bool js_box2dclasses_b2Body_CreateFixture(JSContext *cx, uint32_t argc, JS::Valu JS::RootedValue jsret(cx); if (ret) { // box2d will reuse cached memory, need first remove old proxy when create new jsobject - auto retProxy = jsb_get_native_proxy(ret); - if (retProxy) { - jsb_remove_proxy(retProxy); - } + ScriptingCore::getInstance()->removeObjectProxy(ret); JS::RootedObject retObj(cx); js_get_or_create_jsobject(cx, (b2Fixture*)ret, &retObj); jsret = JS::ObjectOrNullValue(retObj); diff --git a/native/cocos/scripting/js-bindings/manual/creator/js_bindings_creator_manual.cpp b/native/cocos/scripting/js-bindings/manual/creator/js_bindings_creator_manual.cpp index 3940bd9f6e..8d3f538a0c 100644 --- a/native/cocos/scripting/js-bindings/manual/creator/js_bindings_creator_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/creator/js_bindings_creator_manual.cpp @@ -111,10 +111,7 @@ bool js_creator_PhysicsContactListener_setBeginContact(JSContext *cx, uint32_t a JS::RootedValue largv(cx); if (larg0) { // box2d will reuse cached memory, need first remove old proxy when create new jsobject - auto larg0Proxy = jsb_get_native_proxy(larg0); - if (larg0Proxy) { - jsb_remove_proxy(larg0Proxy); - } + ScriptingCore::getInstance()->removeObjectProxy(larg0); JS::RootedObject arg0Obj(cx); js_get_or_create_jsobject(cx, (b2Contact*)larg0, &arg0Obj); largv = JS::ObjectOrNullValue(arg0Obj); From 4722594327c0324bdec062e08b6824dd1e5e298b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 29 Aug 2017 17:52:16 +0800 Subject: [PATCH 05/10] Remove mistaken error log --- .../android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java | 1 - 1 file changed, 1 deletion(-) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java index aa3745f3d6..1568013ee7 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java @@ -234,7 +234,6 @@ public class Cocos2dxEditBoxHelper { if (editBox != null) { mEditBoxArray.remove(index); mFrameLayout.removeView(editBox); - Log.e(TAG, "remove EditBox"); } } }); From 703e857352ff648a23db0007e6a12fecef69439f Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 30 Aug 2017 13:56:41 +0800 Subject: [PATCH 06/10] Synchronize network changes from cocos2d-x. --- native/cocos/network/CCDownloader-android.cpp | 51 ++- native/cocos/network/CCDownloader-android.h | 2 +- native/cocos/network/CCDownloader-apple.h | 2 +- native/cocos/network/CCDownloader-apple.mm | 30 +- native/cocos/network/CCDownloader-curl.cpp | 5 +- native/cocos/network/CCDownloader-curl.h | 2 +- native/cocos/network/CCDownloader.cpp | 10 +- native/cocos/network/CCIDownloaderImpl.h | 2 +- .../cocos/network/HttpAsynConnection-apple.h | 2 +- .../cocos/network/HttpAsynConnection-apple.m | 56 ++-- native/cocos/network/HttpClient-android.cpp | 308 +++++++++++------- native/cocos/network/HttpClient-apple.mm | 67 ++-- native/cocos/network/HttpClient.cpp | 73 +++-- native/cocos/network/HttpClient.h | 4 +- native/cocos/network/HttpCookie.cpp | 34 +- native/cocos/network/HttpCookie.h | 2 +- native/cocos/network/HttpRequest.h | 16 +- native/cocos/network/HttpResponse.h | 13 +- .../lib/Cocos2dxHttpURLConnection.java | 3 + 19 files changed, 395 insertions(+), 287 deletions(-) diff --git a/native/cocos/network/CCDownloader-android.cpp b/native/cocos/network/CCDownloader-android.cpp index 08f61bf7b8..d24fcb576f 100644 --- a/native/cocos/network/CCDownloader-android.cpp +++ b/native/cocos/network/CCDownloader-android.cpp @@ -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 + #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 sDownloaderMap; +std::mutex sDownloaderMutex; + +static void _insertDownloaderAndroid(int id, cocos2d::network::DownloaderAndroid* downloaderPtr) +{ + std::lock_guard guard(sDownloaderMutex); + sDownloaderMap.insert(make_pair(id, downloaderPtr)); +} + +static void _eraseDownloaderAndroid(int id) +{ + std::lock_guard guard(sDownloaderMutex); + sDownloaderMap.erase(id); +} + +/** + * If not found, return nullptr, otherwise return the Downloader + */ +static cocos2d::network::DownloaderAndroid* _findDownloaderAndroid(int id) +{ + std::lock_guard 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 buf; if (errStr) { diff --git a/native/cocos/network/CCDownloader-android.h b/native/cocos/network/CCDownloader-android.h index 868f602736..d820fd8e6a 100644 --- a/native/cocos/network/CCDownloader-android.h +++ b/native/cocos/network/CCDownloader-android.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader-apple.h b/native/cocos/network/CCDownloader-apple.h index 7c08eb47a9..fd087d260d 100644 --- a/native/cocos/network/CCDownloader-apple.h +++ b/native/cocos/network/CCDownloader-apple.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader-apple.mm b/native/cocos/network/CCDownloader-apple.mm index 0613d7df30..8d67db6d96 100644 --- a/native/cocos/network/CCDownloader-apple.mm +++ b/native/cocos/network/CCDownloader-apple.mm @@ -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 +#import // 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 data((size_t)buflen); + char* buf = (char*)data.data(); [wrapper transferDataToBuffer:buf lengthOfBuffer:buflen]; - std::vector 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 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(); diff --git a/native/cocos/network/CCDownloader-curl.cpp b/native/cocos/network/CCDownloader-curl.cpp index 5567296a26..c842a743f1 100644 --- a/native/cocos/network/CCDownloader-curl.cpp +++ b/native/cocos/network/CCDownloader-curl.cpp @@ -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; diff --git a/native/cocos/network/CCDownloader-curl.h b/native/cocos/network/CCDownloader-curl.h index 4cfe5e3dda..b5d924cd3b 100644 --- a/native/cocos/network/CCDownloader-curl.h +++ b/native/cocos/network/CCDownloader-curl.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader.cpp b/native/cocos/network/CCDownloader.cpp index bce110f4b3..6dbf6b3bac 100644 --- a/native/cocos/network/CCDownloader.cpp +++ b/native/cocos/network/CCDownloader.cpp @@ -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& transferDataToBuffer) + std::function& /*transferDataToBuffer*/) { if (onTaskProgress) { diff --git a/native/cocos/network/CCIDownloaderImpl.h b/native/cocos/network/CCIDownloaderImpl.h index 82a9465aa2..098ddd8832 100644 --- a/native/cocos/network/CCIDownloaderImpl.h +++ b/native/cocos/network/CCIDownloaderImpl.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpAsynConnection-apple.h b/native/cocos/network/HttpAsynConnection-apple.h index df370a91e9..573f37d211 100644 --- a/native/cocos/network/HttpAsynConnection-apple.h +++ b/native/cocos/network/HttpAsynConnection-apple.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpAsynConnection-apple.m b/native/cocos/network/HttpAsynConnection-apple.m index 51c83b41ab..c80e278302 100755 --- a/native/cocos/network/HttpAsynConnection-apple.m +++ b/native/cocos/network/HttpAsynConnection-apple.m @@ -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 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]; diff --git a/native/cocos/network/HttpClient-android.cpp b/native/cocos/network/HttpClient-android.cpp index 79c2d27da4..da57b379dc 100644 --- a/native/cocos/network/HttpClient-android.cpp +++ b/native/cocos/network/HttpClient-android.cpp @@ -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 HttpRequestHeaders; typedef HttpRequestHeaders::iterator HttpRequestHeadersIter; typedef std::vector 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 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 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::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 * recvBuffer = (std::vector*)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 @@ -820,11 +888,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; } @@ -857,7 +925,7 @@ void HttpClient::destroyInstance() CCLOG("HttpClient::destroyInstance() finished!"); } -void HttpClient::enableCookies(const char* cookieFile) +void HttpClient::enableCookies(const char* cookieFile) { std::lock_guard lock(_cookieFileMutex); if (cookieFile) @@ -869,7 +937,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt"); } } - + void HttpClient::setSSLVerification(const std::string& caFile) { std::lock_guard lock(_sslCaFileMutex); @@ -877,12 +945,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(); @@ -896,7 +964,7 @@ HttpClient::~HttpClient() } //Lazy create semaphore & mutex & thread -bool HttpClient::lazyInitThreadSemphore() +bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { @@ -914,17 +982,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(); @@ -956,7 +1024,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()) @@ -966,7 +1034,7 @@ void HttpClient::dispatchResponseCallbacks() } _responseQueueMutex.unlock(); - + if (response) { HttpRequest *request = response->getHttpRequest(); @@ -982,7 +1050,7 @@ void HttpClient::dispatchResponseCallbacks() { (pTarget->*pSelector)(this, response); } - + response->release(); // do not release in other thread request->release(); @@ -1005,7 +1073,7 @@ void HttpClient::decreaseThreadCountAndMayDeleteThis() { needDeleteThis = true; } - + _threadCountMutex.unlock(); if (needDeleteThis) { @@ -1018,31 +1086,31 @@ void HttpClient::setTimeoutForConnect(int value) std::lock_guard lock(_timeoutForConnectMutex); _timeoutForConnect = value; } - + int HttpClient::getTimeoutForConnect() { std::lock_guard lock(_timeoutForConnectMutex); return _timeoutForConnect; } - + void HttpClient::setTimeoutForRead(int value) { std::lock_guard lock(_timeoutForReadMutex); _timeoutForRead = value; } - + int HttpClient::getTimeoutForRead() { std::lock_guard lock(_timeoutForReadMutex); return _timeoutForRead; } - + const std::string& HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } - + const std::string& HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index aa9619a4e5..534f4de695 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -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); @@ -112,7 +113,7 @@ void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response const ccHttpRequestCallback& callback = request->getCallback(); Ref* pTarget = request->getTarget(); SEL_HttpResponse pSelector = request->getSelector(); - + if (callback != nullptr) { callback(this, response); @@ -138,7 +139,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]; @@ -146,7 +147,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque NSMutableURLRequest *nsrequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:HttpClient::getInstance()->getTimeoutForConnect()]; - + //set request type [nsrequest setHTTPMethod:requestType]; @@ -155,12 +156,12 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque if(!headers.empty()) { /* append custom headers one by one */ - for (std::vector::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]; @@ -169,7 +170,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()) { @@ -195,34 +196,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) { @@ -237,9 +238,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()) { @@ -254,7 +255,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]; @@ -263,11 +264,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]; @@ -363,12 +364,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); @@ -389,7 +390,7 @@ HttpClient::~HttpClient() } //Lazy create semaphore & mutex & thread -bool HttpClient::lazyInitThreadSemphore() +bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { @@ -408,7 +409,7 @@ bool HttpClient::lazyInitThreadSemphore() //Add a get task to queue void HttpClient::send(HttpRequest* request) { - if (false == lazyInitThreadSemphore()) + if (false == lazyInitThreadSemaphore()) { return; } @@ -507,7 +508,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; } diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index b196aa074f..5e86c77cf1 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -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 *recvBuffer = (std::vector*)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 *recvBuffer = (std::vector*)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(); @@ -173,7 +173,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) { @@ -197,9 +197,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, ""); @@ -253,8 +253,8 @@ public: if(!headers.empty()) { /* append custom headers one by one */ - for (std::vector::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; @@ -274,7 +274,7 @@ public: && setOption(CURLOPT_WRITEDATA, stream) && setOption(CURLOPT_HEADERFUNCTION, headerCallback) && setOption(CURLOPT_HEADERDATA, headerStream); - + } /// @param responseCode Null not allowed @@ -288,7 +288,7 @@ public: return false; } // Get some mor data. - + return true; } }; @@ -345,7 +345,7 @@ HttpClient* HttpClient::getInstance() { _httpClient = new (std::nothrow) HttpClient(); } - + return _httpClient; } @@ -388,7 +388,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt"); } } - + void HttpClient::setSSLVerification(const std::string& caFile) { std::lock_guard lock(_sslCaFileMutex); @@ -396,12 +396,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)); @@ -416,7 +416,7 @@ HttpClient::~HttpClient() } //Lazy create semaphore & mutex & thread -bool HttpClient::lazyInitThreadSemphore() +bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { @@ -428,23 +428,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(); @@ -484,7 +484,7 @@ void HttpClient::dispatchResponseCallbacks() _responseQueue.erase(0); } _responseQueueMutex.unlock(); - + if (response) { HttpRequest *request = response->getHttpRequest(); @@ -500,7 +500,7 @@ void HttpClient::dispatchResponseCallbacks() { (pTarget->*pSelector)(this, response); } - + response->release(); // do not release in other thread request->release(); @@ -558,7 +558,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; } @@ -604,31 +604,31 @@ void HttpClient::setTimeoutForConnect(int value) std::lock_guard lock(_timeoutForConnectMutex); _timeoutForConnect = value; } - + int HttpClient::getTimeoutForConnect() { std::lock_guard lock(_timeoutForConnectMutex); return _timeoutForConnect; } - + void HttpClient::setTimeoutForRead(int value) { std::lock_guard lock(_timeoutForReadMutex); _timeoutForRead = value; } - + int HttpClient::getTimeoutForRead() { std::lock_guard lock(_timeoutForReadMutex); return _timeoutForRead; } - + const std::string& HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } - + const std::string& HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); @@ -639,3 +639,4 @@ const std::string& HttpClient::getSSLVerification() NS_CC_END + diff --git a/native/cocos/network/HttpClient.h b/native/cocos/network/HttpClient.h index b59ef81f71..58a0743743 100644 --- a/native/cocos/network/HttpClient.h +++ b/native/cocos/network/HttpClient.h @@ -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 @@ -158,7 +158,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 **/ diff --git a/native/cocos/network/HttpCookie.cpp b/native/cocos/network/HttpCookie.cpp index 3c8b60704c..cf9a4f864f 100644 --- a/native/cocos/network/HttpCookie.cpp +++ b/native/cocos/network/HttpCookie.cpp @@ -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* 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()); diff --git a/native/cocos/network/HttpCookie.h b/native/cocos/network/HttpCookie.h index 86450d79cb..ab81795b04 100644 --- a/native/cocos/network/HttpCookie.h +++ b/native/cocos/network/HttpCookie.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpRequest.h b/native/cocos/network/HttpRequest.h index e018548077..1dd0a8ac20 100644 --- a/native/cocos/network/HttpRequest.h +++ b/native/cocos/network/HttpRequest.h @@ -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 @@ -78,17 +78,17 @@ 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. */ HttpRequest() - : _requestType(Type::UNKNOWN) - , _pTarget(nullptr) - , _pSelector(nullptr) - , _pCallback(nullptr) - , _pUserData(nullptr) + : _requestType(Type::UNKNOWN) + , _pTarget(nullptr) + , _pSelector(nullptr) + , _pCallback(nullptr) + , _pUserData(nullptr) { } @@ -365,7 +365,7 @@ protected: SEL_HttpResponse _pSelector; /// callback function, e.g. MyLayer::onHttpResponse(HttpClient *sender, HttpResponse * response) ccHttpRequestCallback _pCallback; /// C++11 style callbacks void* _pUserData; /// You can add your customed data here - std::vector _headers; /// custom http headers + std::vector _headers; /// custom http headers }; } diff --git a/native/cocos/network/HttpResponse.h b/native/cocos/network/HttpResponse.h index efbae4bfe4..f73eaba0e5 100644 --- a/native/cocos/network/HttpResponse.h +++ b/native/cocos/network/HttpResponse.h @@ -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); } /** diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java index 33bdac6759..adfb8c599a 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java @@ -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; From 672d00478f7b8c539b0674df34b78f5d29202e8d Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Fri, 1 Sep 2017 11:18:27 +0800 Subject: [PATCH 07/10] fixed android-studio debug error --- .../runtime-src/proj.android-studio/app/build.gradle | 4 ++-- .../runtime-src/proj.android-studio/app/build.gradle | 4 ++-- .../runtime-src/proj.android-studio/app/build.gradle | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle index ed5f955c60..0d0dbe18ae 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -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() } diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle index b041b142c3..2ee236b04f 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -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() } diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle index ed5f955c60..0d0dbe18ae 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -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() } From 97b52f38cb32ed507f4d1a06a23ffb182f6fe64c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 1 Sep 2017 18:07:14 +0800 Subject: [PATCH 08/10] Fix JS_EncodeStringToUTF8 memory leak --- .../cocos/scripting/js-bindings/manual/ScriptingCore.cpp | 9 +++++++-- .../js-bindings/manual/js_manual_conversions.cpp | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 92bb5c24b2..4587b3edec 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -1041,8 +1041,13 @@ void ScriptingCore::reportError(JSContext *cx, JSErrorReport *report, JS::Handle if (JS_GetProperty(cx, errObj, "stack", &stack) && stack.isString()) { JS::RootedString jsstackStr(cx, stack.toString()); - stackStr = JS_EncodeStringToUTF8(cx, jsstackStr); - CCLOGERROR("Stack: %s\n", stackStr.c_str()); + char *rawStr = JS_EncodeStringToUTF8(cx, jsstackStr); + if (rawStr != nullptr) + { + stackStr = rawStr; + JS_free(cx, rawStr); + CCLOGERROR("Stack: %s\n", stackStr.c_str()); + } } } diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp index 21339c1b56..47fbfcc38e 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp @@ -79,13 +79,14 @@ void JSStringWrapper::set(JS::HandleValue val, JSContext* cx) } else { - CC_SAFE_DELETE_ARRAY(_buffer); + JS_free(cx, (void*)_buffer); + _buffer = nullptr; } } void JSStringWrapper::set(JS::HandleString str, JSContext* cx) { - CC_SAFE_DELETE_ARRAY(_buffer); + JS_free(cx, (void*)_buffer); if (!cx) { From 0b057318a44ea866f3310aea5ad6631a9da8fc43 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 4 Sep 2017 13:46:37 +0800 Subject: [PATCH 09/10] Avoid useless function check in executeFunctionWithOwner and useless js parameter construction in websocket --- .../js-bindings/manual/ScriptingCore.cpp | 33 ++-- .../manual/network/jsb_websocket.cpp | 147 ++++++++++-------- 2 files changed, 96 insertions(+), 84 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 4587b3edec..c2bdc31560 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -1670,24 +1670,25 @@ bool ScriptingCore::executeFunctionWithOwner(JS::HandleValue owner, const char * JS::RootedValue ownerval(cx, owner); JS::RootedObject obj(cx); if (ownerval.isObject()) - obj = ownerval.toObjectOrNull(); - - do { - if (JS_HasProperty(cx, obj, name, &hasFunc) && hasFunc) { - if (!JS_GetProperty(cx, obj, name, &funcVal)) { - break; + obj = ownerval.toObjectOrNull(); + do + { + if (JS_HasProperty(cx, obj, name, &hasFunc) && hasFunc) { + if (!JS_GetProperty(cx, obj, name, &funcVal)) { + break; + } + if (funcVal.isNullOrUndefined()) { + break; + } + + bRet = JS_CallFunctionValue(cx, obj, funcVal, args, retVal); + if (JS_IsExceptionPending(cx)) { + handlePendingException(cx); + } } - if (funcVal.isNullOrUndefined()) { - break; - } - - bRet = JS_CallFunctionValue(cx, obj, funcVal, args, retVal); - if (JS_IsExceptionPending(cx)) { - handlePendingException(cx); - } - } - }while(0); + } while(0); + } return bRet; } diff --git a/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp b/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp index 032225fd69..cc1e5985d0 100644 --- a/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp +++ b/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp @@ -83,23 +83,25 @@ public: return; JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - - // Set the protocol which server selects. - JS::RootedValue jsprotocol(cx); - std_string_to_jsval(cx, ws->getProtocol(), &jsprotocol); - JS::RootedObject wsObj(cx, p->obj); - JS_SetProperty(cx, wsObj, "protocol", jsprotocol); - - JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); - JS::RootedValue vp(cx); - c_string_to_jsval(cx, "open", &vp); - JS_SetProperty(cx, jsobj, "type", vp); - - JS::RootedValue jsobjVal(cx, JS::ObjectOrNullValue(jsobj)); - JS::HandleValueArray args(jsobjVal); JS::RootedValue owner(cx, JS::ObjectOrNullValue(_JSDelegate)); - - ScriptingCore::getInstance()->executeFunctionWithOwner(owner, "onopen", args); + if (owner.isObject()) + { + // Set the protocol which server selects. + JS::RootedValue jsprotocol(cx); + std_string_to_jsval(cx, ws->getProtocol(), &jsprotocol); + JS::RootedObject wsObj(cx, p->obj); + JS_SetProperty(cx, wsObj, "protocol", jsprotocol); + + JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); + JS::RootedValue vp(cx); + c_string_to_jsval(cx, "open", &vp); + JS_SetProperty(cx, jsobj, "type", vp); + + JS::RootedValue jsobjVal(cx, JS::ObjectOrNullValue(jsobj)); + JS::HandleValueArray args(jsobjVal); + + ScriptingCore::getInstance()->executeFunctionWithOwner(owner, "onopen", args); + } } virtual void onMessage(WebSocket* ws, const WebSocket::Data& data) @@ -111,46 +113,49 @@ public: return; JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); - JS::RootedValue vp(cx); - c_string_to_jsval(cx, "message", &vp); - JS_SetProperty(cx, jsobj, "type", vp); - - JS::RootedValue arg(cx, JS::ObjectOrNullValue(jsobj)); - bool flag; - if (data.isBinary) - {// data is binary - JS::RootedObject buffer(cx, JS_NewArrayBuffer(cx, static_cast(data.len))); - if (data.len > 0) - { - uint8_t* bufdata = JS_GetArrayBufferData(buffer, &flag, JS::AutoCheckCannotGC()); - memcpy((void*)bufdata, (void*)data.bytes, data.len); - } - JS::RootedValue dataVal(cx, JS::ObjectOrNullValue(buffer)); - JS_SetProperty(cx, jsobj, "data", dataVal); - } - else - {// data is string - JS::RootedValue dataVal(cx); - if (strlen(data.bytes) == 0 && data.len > 0) - {// String with 0x00 prefix - dataVal = JS::StringValue(JS_NewStringCopyN(cx, data.bytes, data.len)); + JS::RootedValue delegate(cx, JS::ObjectOrNullValue(_JSDelegate)); + if (delegate.isObject()) + { + JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); + JS::RootedValue vp(cx); + c_string_to_jsval(cx, "message", &vp); + JS_SetProperty(cx, jsobj, "type", vp); + + JS::RootedValue arg(cx, JS::ObjectOrNullValue(jsobj)); + bool flag; + if (data.isBinary) + {// data is binary + JS::RootedObject buffer(cx, JS_NewArrayBuffer(cx, static_cast(data.len))); + if (data.len > 0) + { + uint8_t* bufdata = JS_GetArrayBufferData(buffer, &flag, JS::AutoCheckCannotGC()); + memcpy((void*)bufdata, (void*)data.bytes, data.len); + } + JS::RootedValue dataVal(cx, JS::ObjectOrNullValue(buffer)); + JS_SetProperty(cx, jsobj, "data", dataVal); } else - {// Normal string - c_string_to_jsval(cx, data.bytes, &dataVal); + {// data is string + JS::RootedValue dataVal(cx); + if (strlen(data.bytes) == 0 && data.len > 0) + {// String with 0x00 prefix + dataVal = JS::StringValue(JS_NewStringCopyN(cx, data.bytes, data.len)); + } + else + {// Normal string + c_string_to_jsval(cx, data.bytes, &dataVal); + } + if (dataVal.isNullOrUndefined()) + { + ws->closeAsync(); + return; + } + JS_SetProperty(cx, jsobj, "data", dataVal); } - if (dataVal.isNullOrUndefined()) - { - ws->closeAsync(); - return; - } - JS_SetProperty(cx, jsobj, "data", dataVal); - } - JS::RootedValue delegate(cx, JS::ObjectOrNullValue(_JSDelegate)); - JS::HandleValueArray args(arg); - ScriptingCore::getInstance()->executeFunctionWithOwner(delegate, "onmessage", args); + JS::HandleValueArray args(arg); + ScriptingCore::getInstance()->executeFunctionWithOwner(delegate, "onmessage", args); + } } virtual void onClose(WebSocket* ws) @@ -161,15 +166,18 @@ public: if (cocos2d::Director::getInstance() != nullptr && cocos2d::Director::getInstance()->getRunningScene() && cocos2d::ScriptEngineManager::getInstance() != nullptr) { JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); - JS::RootedValue vp(cx); - c_string_to_jsval(cx, "close", &vp); - JS_SetProperty(cx, jsobj, "type", vp); - JS::RootedValue delegate(cx, JS::ObjectOrNullValue(_JSDelegate)); - JS::RootedValue arg(cx, JS::ObjectOrNullValue(jsobj)); - JS::HandleValueArray args(arg); - ScriptingCore::getInstance()->executeFunctionWithOwner(delegate, "onclose", args); + if (delegate.isObject()) + { + JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); + JS::RootedValue vp(cx); + c_string_to_jsval(cx, "close", &vp); + JS_SetProperty(cx, jsobj, "type", vp); + + JS::RootedValue arg(cx, JS::ObjectOrNullValue(jsobj)); + JS::HandleValueArray args(arg); + ScriptingCore::getInstance()->executeFunctionWithOwner(delegate, "onclose", args); + } } JS_SetPrivate(p->obj, nullptr); } @@ -186,15 +194,18 @@ public: return; JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); - JS::RootedValue vp(cx); - c_string_to_jsval(cx, "error", &vp); - JS_SetProperty(cx, jsobj, "type", vp); - JS::RootedValue delegate(cx, JS::ObjectOrNullValue(_JSDelegate)); - JS::RootedValue arg(cx, JS::ObjectOrNullValue(jsobj)); - JS::HandleValueArray args(arg); - ScriptingCore::getInstance()->executeFunctionWithOwner(delegate, "onerror", args); + if (delegate.isObject()) + { + JS::RootedObject jsobj(cx, JS_NewPlainObject(cx)); + JS::RootedValue vp(cx); + c_string_to_jsval(cx, "error", &vp); + JS_SetProperty(cx, jsobj, "type", vp); + + JS::RootedValue arg(cx, JS::ObjectOrNullValue(jsobj)); + JS::HandleValueArray args(arg); + ScriptingCore::getInstance()->executeFunctionWithOwner(delegate, "onerror", args); + } } void setJSDelegate(JS::HandleObject pJSDelegate) From 087f1f8c8d3f008d0b5dd284a02954bc45a243d9 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 7 Sep 2017 17:48:48 +0800 Subject: [PATCH 10/10] Remove inappropriate logs in debugger --- .../scripting/js-bindings/script/debugger/actors/breakpoint.js | 1 - .../js-bindings/script/debugger/actors/utils/TabSources.js | 1 - native/cocos/scripting/js-bindings/script/debugger/main.js | 1 - 3 files changed, 3 deletions(-) diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js index ea18c5beb6..758d06d506 100644 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js @@ -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); diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js index 3d865a6ccc..ced3724138 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js @@ -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; } diff --git a/native/cocos/scripting/js-bindings/script/debugger/main.js b/native/cocos/scripting/js-bindings/script/debugger/main.js index 412ed56c36..bacd565861 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/main.js +++ b/native/cocos/scripting/js-bindings/script/debugger/main.js @@ -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 " +