COCO2DX C + + HTTP implementation
The results achieved are as follows
Iphone
Android logs
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdnbpbmdjagfuz3hpbg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">
Flowchart such as the following
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdnbpbmdjagfuz3hpbg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">
function mainly through the Curl C pthread implementation of my implementation is not a multi-threaded breakpoint (assuming to implement can be based on my this to join the task sequence, can refer to the implementation of Cocos2d-x in the Assetsmanager, in fact, my part is also reference this write why write this reason is Assetsmanager is not supported for the continuation of the breakpoint)
Blog Address: http://blog.csdn.net/vpingchangxin/article/details/22309067
Detailed can go to Curl official website or find the information science
PS: Assuming that the version number is published last set timeout of 20 seconds or so the download will take a lot of other download implementation efficiency issues I was trying to test. Set the timeout to 2 seconds
1. First create an interface to control the download, stop, delete, progress and bind events
2. Open a thread in the download (due to the UI, the UI will block the UI thread until the download is complete) The following is an implementation in the control HelloWorldSecene.cpp in the event
void Helloworld::menucallback (ccobject* psender) {Ccmenuitem *item = (Ccmenuitem *) Psender; Switch (Item->gettag ()) {Case 1://Down Start Ccdirector::shareddirector ()->getscheduler ()->s Cheduleselector (Schedule_selector (Helloworld::updateui), this, 0, false); HttpClient in isstop = false; This->threadstart (); Break Case 2://down stop isstop = true; Break Case 3:if (isstop) {cclog ("downfilepath:%s", Downfilepath.c_str ()); if (Access (DOWNFILEPATH.C_STR (), 0) = = 0) {Remove (Downfilepath.c_str ()); Ccmessagebox ("Delete Success", "warm hint"); }else{ccmessagebox ("File Folder not found", "warm hint"); }}else{Ccmessagebox ("Download or no file download", "warm Tip"); } break; Default:break; }}
3. Implementing thread classes and callback settings
method to start thread int Helloworld::threadstart () {pthread_mutex_init (&g_downloadmutex, NULL); int errcode=0; pthread_t Th_curldown; Thread initialization do {pthread_attr_t tattr; Errcode=pthread_attr_init (&TATTR); Cc_break_if (errcode!=0); Errcode=pthread_attr_setdetachstate (&tattr, pthread_create_detached); if (errcode!=0) {Pthread_attr_destroy (&tattr); Break } errcode=pthread_create (&th_curldown, &tattr, thread_funcation, this); } while (0); return Errcode;} The function that requires the completion of the thread is written in this function void* helloworld::thread_funcation (void *arg) {cclog ("thread started ..."); HelloWorld *HW = (helloworld*) arg; HW->CCC = new Curldown ("Http://developer.baidu.com/map/static/doc/output/BaiduMap_AndroidSDK_v2.4.0_All.zip", Hw->downfilepath); Ccc->mdownloadurl = "Http://developer.baidu.com/map/static/doc/output/BaiduMap_AndroidSDK_v2.4.0_All.zip"; int leng = Ccc->getdownloadfilelenth(); Hw->ccc->setdelegate (HW); Hw->ccc->downloadcontroler (); return NULL;}
4. Implement callback progress, success, error (inside the thread lock is used to update the UI of the data progress.) Originally on the thread is unfamiliar, asked the group inside the Daniel, read a lot of information)
void Helloworld::onerror (Curldown::errorcode ErrorCode) {cclog ("error"); Pthread_mutex_lock (&g_downloadmutex); UPDATESTR = "Error"; Pthread_mutex_unlock (&g_downloadmutex); Ccdirector::shareddirector ()->getscheduler ()->unscheduleselector (Schedule_selector (HelloWorld::updateUI) , this);} void Helloworld::onprogress (double percent, void *delegate, String filefullpath) {//Download Progress Cclog ("Donw progress:%.2f%%", percent); if (isstop) {Curldown * cd = (Curldown *) delegate; Pthread_mutex_lock (&g_downloadmutex); Cd->setstopdown (); Pthread_mutex_unlock (&g_downloadmutex); } pthread_mutex_lock (&g_downloadmutex); const char * per =ccstring::createwithformat ("Donw progress:%.2f%%", percent)->getcstring (); Updatestr = per; Downfilepath = Filefullpath; Pthread_mutex_unlock (&g_downloadmutex);} void Helloworld::onsuccess (String filefullpath) {Cclog ("success"); PthRead_mutex_lock (&g_downloadmutex); UPDATESTR = "Success"; Downfilepath = Filefullpath; Pthread_mutex_unlock (&g_downloadmutex);}
The 5.curldown.h CurlDown.cpp class is implemented (can be extracted directly for whatever place, without involving the cocos2d-x part. Cocos2d-x section can be removed okay)
1) Initialize the class
Static pthread_mutex_t g_downloadmutex_1; Curldown::~curldown () { mfilelenth = 0;} Curldown::curldown (): Isstop (False), Mdownloadurl (""), timeout (2) {//test timeout 2 seconds. If release timeout seconds mfilelenth = 0; Mfilepath = ""; Pthread_mutex_init (&g_downloadmutex_1, NULL);} Curldown::curldown (String downurl,string filePath): Mfilelenth (0), Isstop (false), Mdownloadurl (Downurl), timeout (2), Mfilepath (FilePath) { //test timeout 2 seconds. If release timeout-seconds mdownloadurl = Downurl; Pthread_mutex_init (&g_downloadmutex_1, NULL);} void Curldown::setdelegate (Curldowndelegate * delegate) { mdelegate = delegate;}
2) Control Download method
void Curldown::d ownloadcontroler () {Cclog ("--1-"); Mfilelenth = Getdownloadfilelenth (); Get remote File size if (mfilelenth <= 0) {cout << "Download file fail ..." << Endl; Mdelegate->onerror (knetwork); Return } vector<string> searchpaths = Ccfileutils::sharedfileutils ()->getsearchpaths (); Vector<string>::iterator iter = Searchpaths.begin (); Searchpaths.insert (ITER, Mfilepath); Ccfileutils::sharedfileutils ()->setsearchpaths (searchpaths); Cclog ("--2-mfilelenth:%f", mfilelenth); mfilename = Mdownloadurl.substr (Mdownloadurl.rfind ('/') + 1); Cclog ("--3-"); Cclog ("mfilename:%s;", Mfilename.c_str ());//Mfilepath = Ccfileutils::sharedfileutils ()->getwritablepath ();// Cclog ("--5-"); Mfilepath = Mfilepath + mfilename; Cclog ("mfilepath:%s", Mfilepath.c_str ()); Cclog ("--6-"); BOOL ret = FALSE; while (true) {///cycle download every 30 seconds to avoid network-breaking conditions ret = download ();//Direct download for blocking thread Cclog ("----stop---%s------", Isstop? "True": "false"); if (isstop) {//Assume to stop break cclog ("----Stop---------"); Break } if (ret) {//download complete break; } sleep (0.5); Each download intermediate interval 0.5 seconds} if (ret) {cclog ("download OK"); Mdelegate->onsuccess (Mfilepath); } else {cclog ("download Fail"); Mdelegate->onerror (kuncompress); }}
3) Core Download
#pragma mark to download bool Curldown::d ownload () {FILE *FP = NULL; if (Access (MFILEPATH.C_STR (), 0) ==0) {//Append FP = fopen in binary form (MFILEPATH.C_STR (), "ab+"); } else {//binary write FP = fopen (Mfilepath.c_str (), "WB"); } if (fp = = NULL) {//assumes that the file initialization fails to return false; }//read local file download size long localfilelenth = Getlocalfilelength (); The size Cclog ("filepath:%s") has been downloaded. Leng:%ld ", Mfilepath.c_str (), localfilelenth); 4397779//3377875 CURL *handle = Curl_easy_init (); std::string packageurl = Mdownloadurl; + Download file name curl_easy_setopt (handle, Curlopt_url, Packageurl.c_str ()); Http://curl.haxx.se/libcurl/c/fopen.html curl_easy_setopt (handle, Curlopt_timeout, TIMEOUT); Curl_easy_setopt (handle, curlopt_writefunction, My_write_func); Write file callback method curl_easy_setopt (handle, Curlopt_writedata, FP); Write to file Object Curl_easy_setopt (handle, Curlopt_resume_from, localfilelenth); Request data from a local size location//curl_easy_setopt (handle, curlopt_resume_from_lARGE, Localfilelenth); Pit curl_easy_setopt (handle, curlopt_noprogress, 0L); Curl_easy_setopt (handle, curlopt_progressfunction, My_progress_func); Download Progress callback method Curl_easy_setopt (handle, Curlopt_progressdata, this); Pass in this class object Curlcode res = curl_easy_perform (handle); Fclose (FP); return res = = CURLE_OK;}
The following is the source code to ask (^.. ^) source code has been uploaded github https://github.com/pingchangxin/BPDownload cesd download location: http://download.csdn.net/detail/ vpingchangxin/7108649
I'm no longer here Mac she ran to the next door windows in not running (to win cumbersome headache structure)
COCO2DX C + + HTTP implementation