我有以下代码:
void GameScene::onGetServersRequestCompleted( cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response )
{
if( 200 == response->getResponseCode() ) {
std::vector<char> *buffer = response->getResponseData();
std::string serversString( buffer->begin(), buffer->end() );
Json::Reader reader;
Json::Value root;
reader.parse(serversString, root);
const Json::Value servers = root["servers"];
for ( int i = 0; i < servers.size(); ++i ) {
//CCLOG("%s", servers[i].asString().c_str());
cocos2d::network::HttpRequest *request = new cocos2d::network::HttpRequest();
request->setUrl("http://" + servers[i].asString() + "/info");
request->setRequestType(cocos2d::network::HttpRequest::Type::GET);
request->setResponseCallback(CC_CALLBACK_2(GameScene::onServerRequestCompleted, this));
cocos2d::network::HttpClient::getInstance()->send(request);
request->release();
}
} else {
CCLOG("Request Failed! Response Code: %i\n", response->getResponseCode());
/*std::vector<char> *buffer = response->getResponseData();
std::string serversString( buffer->begin(), buffer->end() );
CCLOG("%s", serversString.c_str());*/
this->serverIp = "185.8.166.41";
}
}
我正在尝试获得正确的服务器。我想做的是获取每个服务器请求的执行时间并获得最快的请求。可能吗?因为它是一个异步函数,我不知道该怎么做。你会怎么做?
答案 0 :(得分:1)
这有帮助吗?从文档中 HTTPRequest和HTTPResponse ....
您可以设置字符串标记来标识您的请求,此标记可以在HttpResponse-&gt; getHttpRequest-&gt; getTag()
中找到 void HTTPRequest::setTag(const char *tag);
获取字符串标记以标识请求。 最佳实践是在MyClass :: onMyHttpRequestCompleted(sender,HttpResponse *)回调中使用它
const char* HTTPResponse::getTag();
编辑:您可以使用这些唯一标记将请求与全局哈希中的异步响应配对,从而测量“响应时间”。 HTTP *类中似乎没有任何接口可以为您提供执行时间。
编辑: 有两种方法可以将HTTPResponse与HTTPRequest配对。在这里,我尝试使用第二种方法和一些快速/脏代码。请根据需要转换/使用它。
创建文件HTTPCustomData.h:
#include <time.h>
class HTTPCustomData {
private:
time_t t1;
public:
HTTPCustomData() { time(&t1); }
double getTimePassed(void) {
time_t t2; time(&t2); return(difftime(t2,t1));
}
};
使用以下代码发送请求:
#include "HTTPCustomData.h"
for ( int i = 0; i < servers.size(); ++i ) {
// ...
// ... Before "send"
request->setUserData(new HTTPCustomData());
cocos2d::network::HttpClient::getInstance()->send(request);
request->release();
}
稍后在GameScene :: onServerRequestCompleted方法中,......
#include <memory>
#include <iostream>
#include "HTTPCustomData.h"
void GameScene::onServerRequestCompleted(...) {
{
// ...
std::unique_ptr<HTTPCustomData> h(
(HTTPCustomData *)(response->getHTTPRequst()->getUserData())
);
std::cout << h->getTimePassed() << std::endl;
// ....
}