溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

cocos2d-x學(xué)習(xí)筆記(七)利用curl獲取資源包的大小

發(fā)布時間:2020-08-10 08:22:28 來源:網(wǎng)絡(luò) 閱讀:723 作者:wty530 欄目:游戲開發(fā)

    cocos2d-x將curl作為第三方庫加進(jìn)來,所以我們可以很方便的使用它。

    最近在研究資源熱更新,由于想在用戶更新之前提示資源包大小,讓用戶知道此次更新所需消耗流量,所以在資源熱更新AssetsManager類的基礎(chǔ)上加入獲取資源包大小的代碼。

    我用的是cocos2d-x 3.4的版本,AssetsManager源文件在cocos2d\extensions\assets-manager目錄下。

一、首先在AssetsManager.h文件class AssetsManager底下加入代碼

double _downloadLength;
void loadHead(std::string _fileUrl); 
void onThread(void* curl);
double getDownloadLength();


二、AssetsManager.cpp加入代碼

size_t getHeader(void *ptr, size_t size, size_t nmemb, void *data)
{
return (size_t)(size * nmemb);
}
void AssetsManager::loadHead(std::string _fileUrl)
{
auto curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, _fileUrl.c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);//部分服務(wù)器可能不支持Header響應(yīng)
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, getHeader);//只需要獲取http頭像應(yīng)
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, LOW_SPEED_LIMIT);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, LOW_SPEED_TIME);
auto t = std::thread(&AssetsManager::onThread, this, curl);
t.detach();
}
void AssetsManager::onThread(void* curl)
{
CURLcode res;
do
{
res = curl_easy_perform(curl);
if(res != 0)
{
break;
}
else
{
CURLcode return_code;
long retcode = 0;
//狀態(tài)碼
return_code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &retcode);
log("return_code:%ld", retcode);
if((CURLE_OK != return_code) || !retcode)
{
break;
}
//響應(yīng)內(nèi)容長度
curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &_downloadLength);
log("downLength:%f", _downloadLength);
}
} while (0);
curl_easy_cleanup(curl);
}
double AssetsManager::getDownloadLength()
{
return _downloadLength;
}


loadHead入口函數(shù),參數(shù)為資源包的url地址,getDownloadLength()為獲取到的資源包大小,當(dāng)然,由于計(jì)算資源包大小使用的是多線程,所以,如果你執(zhí)行完loadHead后接著執(zhí)行g(shù)etDownloadLength()有可能獲取的大小是0,因?yàn)橘Y源包大小還沒返回計(jì)算結(jié)果。如果不想用多線程,將以下代碼

auto t = std::thread(&AssetsManager::onThread, this, curl);
t.detach();

改為:

onThread(curl);

即可

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI