加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2d-x学习笔记(七)利用curl获取资源包的大小

发布时间:2020-12-14 17:12:23 所属栏目:百科 来源:网络整理
导读:cocos2d-x将curl作为第三方库加进来,所以我们可以很方便的使用它。 最近在研究资源热更新,由于想在用户更新之前提示资源包大小,让用户知道此次更新所需消耗流量,所以在资源热更新AssetsManager类的基础上加入获取资源包大小的代码。 我用的是cocos2d-x 3

cocos2d-x将curl作为第三方库加进来,所以我们可以很方便的使用它。

最近在研究资源热更新,由于想在用户更新之前提示资源包大小,让用户知道此次更新所需消耗流量,所以在资源热更新AssetsManager类的基础上加入获取资源包大小的代码。

我用的是cocos2d-x 3.4的版本,AssetsManager源文件在cocos2dextensionsassets-manager目录下。

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

double_downloadLength;
voidloadHead(std::string_fileUrl);
voidonThread(void*curl);
doublegetDownloadLength();


二、AssetsManager.cpp加入代码

size_tgetHeader(void*ptr,size_tsize,size_tnmemb,void*data)
{
return(size_t)(size*nmemb);
}
voidAssetsManager::loadHead(std::string_fileUrl)
{
autocurl=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);//部分服务器可能不支持Header响应
curl_easy_setopt(curl,CURLOPT_HEADERFUNCTION,getHeader);//只需要获取http头像应
curl_easy_setopt(curl,CURLOPT_LOW_SPEED_LIMIT,LOW_SPEED_LIMIT);
curl_easy_setopt(curl,CURLOPT_LOW_SPEED_TIME,LOW_SPEED_TIME);
autot=std::thread(&AssetsManager::onThread,this,curl);
t.detach();
}
voidAssetsManager::onThread(void*curl)
{
CURLcoderes;
do
{
res=curl_easy_perform(curl);
if(res!=0)
{
break;
}
else
{
CURLcodereturn_code;
longretcode=0;
//状态码
return_code=curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&retcode);
log("return_code:%ld",retcode);
if((CURLE_OK!=return_code)||!retcode)
{
break;
}
//响应内容长度
curl_easy_getinfo(curl,CURLINFO_CONTENT_LENGTH_DOWNLOAD,&_downloadLength);
log("downLength:%f",_downloadLength);
}
}while(0);
curl_easy_cleanup(curl);
}
doubleAssetsManager::getDownloadLength()
{
return_downloadLength;
}


loadHead入口函数,参数为资源包的url地址,getDownloadLength()为获取到的资源包大小,当然,由于计算资源包大小使用的是多线程,所以,如果你执行完loadHead后接着执行getDownloadLength()有可能获取的大小是0,因为资源包大小还没返回计算结果。如果不想用多线程,将以下代码

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

改为:

onThread(curl);

即可

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读