예제 #1
0
void GameState::onHttpRequestCompleted(CCNode* sender,void *data)
{
	CCHttpResponse *response = (CCHttpResponse*)data;
	if(!response)
		return;

	if( NULL != strlen(response->getHttpRequest()->getTag()))
	{
		CCLog("%s complete.",response->getHttpRequest()->getTag());
	}
	int statusCode = response->getResponseCode();
	CCLog("response code : %d",statusCode);

	if(!response->isSucceed())
	{
		CCLog("response failed");
		CCLog("errorbuffer: %s",response->getErrorBuffer());
		return;
	}
	std::vector<char>* buffer = response->getResponseData();

	char str[200] = {""};
	unsigned int i;

	for(i=0;i<buffer->size();i++)
	{
		str[i] = (*buffer)[i];
	}
	str[i] = '\0';
	CCLog("%s",str);
}
예제 #2
0
void ParseFile::deleteFileFinished(CCNode* sender, void* param)
{
	
	bool success = false;
	ParseError* error = new ParseError();

	CCHttpResponse* response = (CCHttpResponse*)param;
	
	if (response->getResponseCode() == 200)
	{
		success = true;
	}
	else
	{
		if (strlen(response->getErrorBuffer()) > 0)
		{
			error->SetError(response->getErrorBuffer());
		}
		else
		{
			std::vector<char>* responseData = response->getResponseData();
			responseData->push_back('\0');
			error->SetError(&responseData->front());
		}
	}

	this->deleteFileCompleted(success, error);

	delete error;
}
예제 #3
0
void RankScene::getRankListRequestCompleted(CCNode* sender,void* data){
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    
    int counter_name = 0;
    int counter_winPercent = 0;
    int counter_weeklywin = 0;
    
    for (unsigned int i = 0; i < buffer->size(); i++) {
        if ((*buffer)[i] == '"' && (*buffer)[i+1] == 'n' && (*buffer)[i+2] == 'i' && (*buffer)[i+3] == 'c' && (*buffer)[i+4] == 'k' && (*buffer)[i+5] == '"') {
            for (int j = i + 8 ; (*buffer)[j] != '"' ; j++) {   nickName_Rank[counter_name] += (*buffer)[j]; }
            counter_name++;
        }
        if((*buffer)[i] == '"' && (*buffer)[i+1] == 'w' && (*buffer)[i+2] == 'e' && (*buffer)[i+3] == 'e' && (*buffer)[i+4] == 'k' && (*buffer)[i+5] == 'l' && (*buffer)[i+19] == '"') {
            for (int j = i + 21 ; (*buffer)[j] != ',' ; j++) {   winPercent_Rank[counter_winPercent] += (*buffer)[j]; }
            winPercent_Rank[counter_winPercent] = float2string(atof(winPercent_Rank[counter_winPercent].c_str())*100) + "%";
            counter_winPercent++;
        }
        if((*buffer)[i] == '"' && (*buffer)[i+1] == 'w' && (*buffer)[i+2] == 'e' && (*buffer)[i+3] == 'e' && (*buffer)[i+4] == 'k' && (*buffer)[i+5] == 'l' && (*buffer)[i+11] == '"') {
            for (int j = i + 13 ; (*buffer)[j] != ',' ; j++) {   weeklyWin_Rank[counter_weeklywin] += (*buffer)[j]; }
            counter_weeklywin++;
        }
    }
    
    getServerTime();
}
예제 #4
0
파일: ChatLayer.cpp 프로젝트: crazyit/iGame
void ChatLayer::requestFinishedCallback(CCNode* pSender,void *data)
{
    CCHttpResponse *response =  (CCHttpResponse*)data;
	if(response==NULL)
	{
		return;
	}
	int statusCode = response->getResponseCode();
	char statusString[64] = {};
	CCLOG(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());

	if (!response->isSucceed())   
	{  
		CCLog("response failed");  
		CCLog("error buffer: %s", response->getErrorBuffer());  
		return;  
	}
	std::vector<char> *buffer = response->getResponseData(); 

	std::string content(buffer->begin(),buffer->end());

	XMLParser *xmlParser = XMLParser::parseWithString(content.c_str());
	CCLOG("%s",xmlParser->getString("content")->getCString());

//	parseJson();
}
예제 #5
0
void ParseFile::downloadFileFinished(CCNode* sender, void* param)
{
	CCString* savePathName = 0;
	ParseError* error = new ParseError();

	CCHttpResponse* response = (CCHttpResponse*)param;
	
	if (response->getResponseCode() == 200)
	{
		FILE* file = 0;
		const char* errorMsg = 0;
		savePathName = (CCString*)response->getHttpRequest()->getUserData();
		std::vector<char>* responseData = response->getResponseData();
		do
		{
			file = fopen(savePathName->getCString(), "wb");
			if (file == 0)
			{
				errorMsg = "error open file!";
				break;
			}
			size_t writeLen = fwrite(&responseData->front(), 1, responseData->size(), file);
			if (writeLen != responseData->size())
			{
				errorMsg = "error write file!";
				break;
			}
		}while(0);

		if (file)
		{
			fclose(file);
		}
		if (errorMsg)
		{
			error->SetError(errorMsg);
		}
	}
	else
	{
		if (strlen(response->getErrorBuffer()) > 0)
		{
			error->SetError(response->getErrorBuffer());
		}
		else
		{
			std::vector<char>* responseData = response->getResponseData();
			responseData->push_back('\0');
			error->SetError(&responseData->front());
		}
	}

	this->downloadFileCompleted(savePathName?savePathName->getCString():0, error);

	savePathName = (CCString*)response->getHttpRequest()->getUserData();
	savePathName->release();

	delete error;
}
예제 #6
0
void RankScene::getRankRequestCompleted(CCNode* sender,void* data){
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
}
예제 #7
0
void LogInScene::getUserHistoryGameRequestCompleted(CCNode* sender,void* data){
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    
    //1.解析
    string boardIdStr,WinTimesStr,LoseTimesStr;
    for (unsigned int i = 0; i < buffer->size(); i++) {
        //1.排行榜编号
        if ((*buffer)[i] == '"' && (*buffer)[i+1] == 'b' && (*buffer)[i+2] == 'o' && (*buffer)[i+3] == 'a' && (*buffer)[i+4] == 'r') {
            for (int j = i + 11; (*buffer)[j] != ','; j++) {   boardIdStr += (*buffer)[j];    }
        }
        //2.历史胜场
        else if ((*buffer)[i] == '"' && (*buffer)[i+1] == 'h' && (*buffer)[i+2] == 'i' && (*buffer)[i+3] == 's' && (*buffer)[i+4] == 't' && (*buffer)[i+9] == 'w' && (*buffer)[i+12] == '"') {
            for (int j = i + 14; (*buffer)[j] != ','; j++) {   WinTimesStr += (*buffer)[j];    }
        }
        //3.历史败场
        else if ((*buffer)[i] == '"' && (*buffer)[i+1] == 'h' && (*buffer)[i+2] == 'i' && (*buffer)[i+3] == 's' && (*buffer)[i+4] == 't' && (*buffer)[i+9] == 'l' && (*buffer)[i+13] == '"') {
            for (int j = i + 15; (*buffer)[j] != ','; j++) {   LoseTimesStr += (*buffer)[j];    }
        }
        
        //4.如果还没玩过这个
        if ((*buffer)[i] == '4' && (*buffer)[i+1] == '0' && (*buffer)[i+2] == '4') {
            boardNotFound = true;
            break;
        }
    }
    
    //2.计算rank
    if (boardNotFound)
        MainUser->Rank[tmpBoardID] = 0;
    else{
        int _id = atoi(boardIdStr.c_str());
        int WinTimes = atoi(WinTimesStr.c_str());
        int LoseTimes = atoi(LoseTimesStr.c_str());
        MainUser->Rank[tmpBoardID] = MainUser->calculateRank(_id,WinTimes,LoseTimes);
        cout<<_id<<":胜"<<WinTimes<<" 负"<<LoseTimes<<" Rank为"<<MainUser->Rank[tmpBoardID]<<endl;
    }
    
    //3.继续下一个题的rank
    if (tmpBoardID < 14) {
        tmpBoardID++;
        boardNotFound = false;
        getUserHistoryGame(tmpBoardID);
    }
    else
        box->closeMessageBox();
}
예제 #8
0
void ASUser::getHeroInformationRequestCompleted(cocos2d::CCNode *sender, void *data){
    
    for (int i = 0 ; i < 5 ; i++) {
        HeroLevel[i] = 0;
        HeroUnLocked[i] = false;
    }

    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    
    for (unsigned int i = 0; i < buffer->size(); i++) {
        //1.1 第1个英雄的等级情况
        if ((*buffer)[i] == '{' && (*buffer)[i+1] == '"' && (*buffer)[i+2] == 'a' && (*buffer)[i+3] == 'v' && (*buffer)[i+4] == 'a' && (*buffer)[i+13] == '0' && (*buffer)[i+14] == ','){
            HeroUnLocked[0] = true;
            for (int j = i+23;(*buffer)[j] != '}' ; j++) {  HeroLevelStr[0] += (*buffer)[j]; }
        }
        //1.2 第2个英雄的等级情况
        if ((*buffer)[i] == '{' && (*buffer)[i+1] == '"' && (*buffer)[i+2] == 'a' && (*buffer)[i+3] == 'v' && (*buffer)[i+4] == 'a' && (*buffer)[i+13] == '1' && (*buffer)[i+14] == ','){
            HeroUnLocked[1] = true;
            for (int j = i+23;(*buffer)[j] != '}' ; j++) {  HeroLevelStr[1] += (*buffer)[j]; }
        }
        //1.3 第3个英雄的等级情况
        if ((*buffer)[i] == '{' && (*buffer)[i+1] == '"' && (*buffer)[i+2] == 'a' && (*buffer)[i+3] == 'v' && (*buffer)[i+4] == 'a' && (*buffer)[i+13] == '2' && (*buffer)[i+14] == ','){
            HeroUnLocked[2] = true;
            for (int j = i+23;(*buffer)[j] != '}' ; j++) {  HeroLevelStr[2] += (*buffer)[j]; }
        }
        //1.4 第4个英雄的等级情况
        if ((*buffer)[i] == '{' && (*buffer)[i+1] == '"' && (*buffer)[i+2] == 'a' && (*buffer)[i+3] == 'v' && (*buffer)[i+4] == 'a' && (*buffer)[i+13] == '3' && (*buffer)[i+14] == ','){
            HeroUnLocked[3] = true;
            for (int j = i+23;(*buffer)[j] != '}' ; j++) {  HeroLevelStr[3] += (*buffer)[j]; }
        }
        //1.5 第5个英雄的等级情况
        if ((*buffer)[i] == '{' && (*buffer)[i+1] == '"' && (*buffer)[i+2] == 'a' && (*buffer)[i+3] == 'v' && (*buffer)[i+4] == 'a' && (*buffer)[i+13] == '4' && (*buffer)[i+14] == ','){
            HeroUnLocked[4] = true;
            for (int j = i+23;(*buffer)[j] != '}' ; j++) {  HeroLevelStr[4] += (*buffer)[j]; }
        }
    }
    
    for (int i = 0 ; i < 5 ; i++) {
        HeroLevel[i] = atoi(HeroLevelStr[i].c_str())+1;
        cout<<HeroLevel[i]<<" ";
    }
    cout<<endl;
    for (int i = 0 ; i < 5 ; i++) {
        cout<<HeroUnLocked[i]<<" ";
    }
    cout<<endl;
}
예제 #9
0
void S411FeedBack::onPostFinished(CCNode *node,void *data)
{
    AppDelegate::loadingLabel ->setString("");
    _menu->setEnabled(true);
	CCHttpResponse *response = (CCHttpResponse*)data;
	if (!response)
	{
		return;
	}
	int s=response->getHttpRequest()->getRequestType();
	CCLOG("request type %d",s);
    
    
	if (0 != strlen(response->getHttpRequest()->getTag()))
	{
		CCLOG("%s ------>oked", response->getHttpRequest()->getTag());
	}
    
	int statusCode = response->getResponseCode();
	CCLOG("response code: %d", statusCode);
    
    
	char statusString[64] = {};
	sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
	CCLOG("statusString");
    
	if (!response->isSucceed())
	{
		CCLOG("response failed");
		CCLOG("error buffer: %s", response->getErrorBuffer());
        AppDelegate::loadingLabel->setString("提交失败");
        this->schedule(schedule_selector(S411FeedBack::time),1.0f,false,0.0);
		return;
	}
    
    
    
    
	//上面这些都是一些判断是否请求成功,下面这个是获得的请求数据
	std::vector<char> *buffer = response->getResponseData();
	CCLOG("Http Test, dump data: ");
	for (unsigned int i = 0; i < buffer->size(); i++)
	{
		CCLOG("%c", (*buffer)[i]);//这里打印从服务器返回的数据
        
	}
	CCLOG("\n");
    AppDelegate::loadingLabel->setString("提交成功");
    this->schedule(schedule_selector(S411FeedBack::time),1.0f,false,0.0);
}
예제 #10
0
void EziSocialObject::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    
    if (!response)
    {
        CCLOG("[EziSocial Error]: No Response");
    }
    
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        //CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    
    if (!response->isSucceed())
    {
        CCLog("[EziSocial Error]: response failed");
        CCLog("[EziSocial Error]: error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // Dump the data
    std::vector<char> *buffer = response->getResponseData();
    
    // Create the CCSprite from data dump...
    
    CCImage * img=new CCImage();
    img->initWithImageData(&(buffer->front()), buffer->size());
    
    // Save file for resue.
    std::string writablePath = CCFileUtils::sharedFileUtils()->getWritablePath();
    writablePath.append(response->getHttpRequest()->getTag());
    img->saveToFile(writablePath.c_str());
    delete img;
    
    const char* userID = "";
    std::string tagString = "";
    tagString.append(response->getHttpRequest()->getTag());
    
    std::vector< std::string > strings = EziSocialObject::tokenizeStr(tagString, "_");
    userID = strings[0].c_str();
    
    internalUserPhotoCallback(writablePath.c_str(), userID);
}
예제 #11
0
void InGameScene::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
    CCHttpResponse *response = (CCHttpResponse*)data;
    
    if (!response)
    {
        return;
    }
    
    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    //m_labelStatusCode->setString(statusString);
    CCLog("response code: %d", statusCode);
    
    if (!response->isSucceed())
    {
        CCLog("response failed");
        CCLog("error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // dump data
    std::vector<char> *buffer = response->getResponseData();
	std::string s = "";
    bool isDataStarted = false;
    for (unsigned int i = 0; i < buffer->size(); i++)
	{
        if( isDataStarted == false && !isspace((*buffer)[i]) )
            isDataStarted = true;
        if( isDataStarted == false) continue;
        
		s += (*buffer)[i];
    }
	CCLog("%s", s.data() );
    CCLog("\n");
    
    if( strcmp(response->getHttpRequest()->getTag(), "URL_CREATE_ANIMAL") == 0)
    {
        string szAnimalKey = s;
        CCLog("InGameScene::onHttpRequestCompleted-%s : %s", response->getHttpRequest()->getTag(), szAnimalKey.data() );
    }
}
예제 #12
0
void LogInScene::LogInRequestCompleted(CCNode* sender,void* data){
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    if (statusCode == 200) {
        //1.标记为已经登录
        if (!MainUser->hasLogIn) {
            MainUser->hasLogIn = true;
            BeginMenuFallDown();  //关闭网络,进入游戏,没有按钮掉下来,再打开网络,重新登录以后,要掉下来
        }
        //2.记录服务器发回的信息
        if(!MainUser->initUser(buffer))
            MainUser->hasChosenHero = false;
        else
            MainUser->hasChosenHero = true;
        saveLogInInformation(UserNameStr,PassWordStr);
        //3.初始化rank
        tmpBoardID = 0;
        getUserHistoryGame(tmpBoardID);
    }
    else{
        if(statusCode == 401){
            box->closeMessageBox();
            box = AsMessageBox::createMessageBox("用户名与密码不匹配", 2, 1);
            box->setPosition(CCPointZero);
            addChild(box,100);
        }
        else if(statusCode == 404){
            box->closeMessageBox();
            box = AsMessageBox::createMessageBox("该用户不存在", 2, 1);
            box->setPosition(CCPointZero);
            addChild(box,100);
        }
        else{
            box->closeMessageBox();
            box = AsMessageBox::createMessageBox("无法连接,请检查您的网络", 2, 1);
            box->setPosition(CCPointZero);
            addChild(box,100);
        }
    }
}
예제 #13
0
void MyHttpRequest::onHttpRequestCompleted(CCNode *sender,void *data)  
{  
	m_isCompleted=true;
	CCHttpResponse *response = (CCHttpResponse*)data;  
	if (!response)  
	{  
		return;  
	}  
	int s=response->getHttpRequest()->getRequestType();  
	CCLog("request type %d",s);  


	if (0 != strlen(response->getHttpRequest()->getTag()))   
	{  
		CCLog("%s ------>oked", response->getHttpRequest()->getTag());  
	}  

	int statusCode = response->getResponseCode();  
	CCLog("response code: %d", statusCode);  


	char statusString[64] = {};  
	sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());  
	CCLog(statusString);  

	if (!response->isSucceed())   
	{  
		CCLog("response failed");  
		CCLog("error buffer: %s", response->getErrorBuffer());  
		return;  
	}  

	std::vector<char> *buffer = response->getResponseData(); 
	printf("Http Test, dump data: ");  
	for (unsigned int i = 0; i < buffer->size(); i++)  
	{  
		//CCLog("%c", (*buffer)[i]);//这里打印从服务器返回的数据  
		m_responseData.push_back((*buffer)[i]);
	}  
	CCLog("m_responseData:%s",m_responseData.c_str());
	printf("\n");  

} 
예제 #14
0
void CLoginScene::urlCallback(CCNode *sender ,void *data)
{
	CSceneManager::sharedSceneManager()->closePopupBox(GETBOX(CLoadingBox));
	CCHttpResponse* response = (CCHttpResponse*) data;
	if (!response) 
	{
		CSceneManager::sharedSceneManager()->openPopupBox(GETBOX(CMessageBox), (void*)"failure");
		return;
	}
	int statusCode = response->getResponseCode();
	if (response->isSucceed()) 
	{
		
		CSceneManager::sharedSceneManager()->openPopupBox(GETBOX(CMessageBox), (void*)"success");
	} else 
	{
		CSceneManager::sharedSceneManager()->openPopupBox(GETBOX(CMessageBox), (void*)"failure");
	}
}
예제 #15
0
void ParseFile::uploadFileContentFinished(CCNode* sender, void* param)
{
	FileInfo* result = 0;
	ParseError* error = new ParseError();

	CCHttpResponse* response = (CCHttpResponse*)param;
	
	if (response->getResponseCode() == 201)
	{
		rapidjson::Document retValue;
		if(ParseJson::FromByteArray(*response->getResponseData(), retValue, error))
		{
			if (retValue.HasMember("url"))
			{
				result = new FileInfo(retValue["url"].GetString(), retValue["name"].GetString());
			}
		}
		if (result == 0)
		{
			std::vector<char>* responseData = response->getResponseData();
			responseData->push_back('\0');
			error->SetError(error->GetError() + "data:" + &responseData->front());
		}
	}
	else
	{
		if (strlen(response->getErrorBuffer()) > 0)
		{
			error->SetError(response->getErrorBuffer());
		}
		else
		{
			std::vector<char>* responseData = response->getResponseData();
			responseData->push_back('\0');
			error->SetError(&responseData->front());
		}
	}

	this->uploadFileContentCompleted(result, error);

	delete error;
}
예제 #16
0
void RankScene::unlockHeroRequestCompleted(cocos2d::CCNode *sender, void *data){
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    if (statusCode == 201) {
        changeGold(-MainUser->HeroUnLockPrice[HeroProcessing]);
        MainUser->HeroUnLocked[HeroProcessing] = true;
        UnlockAnimation(HeroProcessing);
        goldProcessingIndex = 4;
        updateUserGold();
    }
    else{
        MessageBox->closeMessageBox();
        MessageBox = AsMessageBox::createMessageBox("与服务器通信失败,\n请检查您的网络", 2, 1);
        MessageBox->setPosition(CCPointZero);
        addChild(MessageBox,1000);
    }
}
	void responseCallback(cocos2d::CCNode *sender, void *data){
		CCHttpResponse *response = (CCHttpResponse*)data; 

		if (!response) 
		{ 
			CCLog("no response...");
			return; 
		} 

		int statusCode = response->getResponseCode(); 
		char statusString[64] = {}; 
		sprintf(statusString, "HTTP Status Code: %d", statusCode); 
		
		CCLOG("response code: %d", statusCode); 

		if (!response->isSucceed())  
		{ 
			CCLOG("response failed"); 
			CCLOG("error buffer: %s", response->getErrorBuffer()); 

			JsonData* msg = new JsonData();
			(*msg)["data"] = response->getErrorBuffer();
			PROXY_FIRE("error", msg);
			CC_SAFE_DELETE(msg);

			return; 
		}

		// dump data 
		std::vector<char> *buffer = response->getResponseData(); 
		//std::string path = CCFileUtils::sharedFileUtils()->getWriteablePath(); 
		std::string buf(buffer->begin(),buffer->end()); 

		JsonData* msg = new JsonData();
		(*msg)["data"] = buf.c_str();
		PROXY_FIRE("complete", msg);
		CC_SAFE_DELETE(msg);
	};
예제 #18
0
void RankScene::HeroLevelUpRequestCompleted(CCNode* sender,void* data){
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    
    if (statusCode == 204) {
        changeGold(-MainUser->HeroLevelUpGold[MainUser->HeroLevel[roleIndex-1]-1]);
        MainUser->HeroLevel[roleIndex-1]++;
        LevelUpAnimation(roleIndex-1);
        
        goldProcessingIndex = 4;
        updateUserGold();
    }
    else{
        MessageBox->closeMessageBox();
        MessageBox = AsMessageBox::createMessageBox("与服务器通信失败,\n请检查您的网络", 2, 1);
        MessageBox->setPosition(CCPointZero);
        addChild(MessageBox,1000);
    }
}
예제 #19
0
void HttpClientTest::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
    CCHttpResponse *response = (CCHttpResponse*)data;

    if (!response)
    {
        return;
    }
    
    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag())) 
    {
        CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    m_labelStatusCode->setString(statusString);
    CCLog("response code: %d", statusCode);
    
    if (!response->isSucceed()) 
    {
        CCLog("response failed");
        CCLog("error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // dump data
    std::vector<char> *buffer = response->getResponseData();
    printf("Http Test, dump data: ");
    for (unsigned int i = 0; i < buffer->size(); i++)
    {
        printf("%c", (*buffer)[i]);
    }
    printf("\n");
}
예제 #20
0
void RankScene::getServerTimeRequestCompleted(cocos2d::CCNode *sender, void *data){
    
    year_current = month_current = day_current = clock_current = minute_current = second_current = "";
    
    //1.获取服务器返回的时间信息
    CCHttpResponse* response = (CCHttpResponse*)data;
    if (!response) {    return;     }
    int statusCode = response->getResponseCode();
    std::vector<char> *buffer = response->getResponseData();
    printJson(buffer);
    
    //2.解析时间信息
    string expStr;
    int now,exp;
    for (unsigned int i = 0; i < buffer->size(); i++) {
        //2.1 当前时间
        if ((*buffer)[i] == '"' && (*buffer)[i+1] == 'n' && (*buffer)[i+2] == 'o' && (*buffer)[i+3] == 'w' && (*buffer)[i+4] == '"' && (*buffer)[i+5] == ':'){
            for (int j = 0 ; j < 4 ; j++)
                year_current += (*buffer)[i+7+j];
            for (int j = 0 ; j < 2 ; j++){
                month_current += (*buffer)[i+12+j];
                day_current += (*buffer)[i+15+j];
                clock_current += (*buffer)[i+18+j];
                minute_current += (*buffer)[i+21+j];
                second_current += (*buffer)[i+24+j];
            }
        }
        //2.2 结算时间
        if((*buffer)[i] == 'a' && (*buffer)[i+1] == 't' && (*buffer)[i+2] == '"' && (*buffer)[i+3] == ':' && (*buffer)[i+4] == '"' && (*buffer)[i+5] == '2')
            for (int j = 0;  j < 2 ; j++)
                expStr += (*buffer)[i+13+j];
    }
    
    //3.计算下次结算时间
    int daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if (day_current[0] == 0)
        now = atoi(&day_current[1]);
    else
        now = atoi(day_current.c_str());
    if (expStr[0] == 0)
        exp = atoi(&expStr[1]);
    else
        exp = atoi(expStr.c_str());
    if (exp < now) {
        serverTime = exp + daysPerMonth[atoi(month_current.c_str())-1] - now;
    }else
        serverTime = exp - now;
    
    //4.计算下次回复时间,总的秒数
    int nextSecond = 0;
    if (year_next!="" && month_next!="" && day_next!="" && clock_next!="" && minute_next!="" && second_next!="") {
        nextSecond += atoi(year_next.c_str())*31536000;
        for (int i = 0 ; i < atoi(month_next.c_str()); i++)
            nextSecond += daysPerMonth[i]*24*60*60;
        nextSecond += atoi(day_next.c_str())*24*60*60;
        nextSecond += atoi(clock_next.c_str())*60*60;
        nextSecond += atoi(minute_next.c_str())*60;
        nextSecond += atoi(second_next.c_str());
    }else
        nextSecond = 0;
    
    //5.计算当前的时间,总的秒数
    int currentSecond = 0;
    if (nextSecond!=0) {
        currentSecond += atoi(year_current.c_str())*31536000;
        for (int i = 0 ; i < atoi(month_current.c_str()); i++)
            currentSecond += daysPerMonth[i]*24*60*60;
        currentSecond += atoi(day_current.c_str())*24*60*60;
        currentSecond += atoi(clock_current.c_str())*60*60;
        currentSecond += atoi(minute_current.c_str())*60;
        currentSecond += atoi(second_current.c_str());
    }else
        currentSecond = 0;
        
    nextRecoverySecond = nextSecond - currentSecond;
    
    //6.体力部分
    for (int i = 0 ; i < 6 ; i++)
        removeChildByTag(41+i);

    for (int i = 0 ; i < MainUser->energyNumber ; i++) {
        CCSprite* energy = CCSprite::createWithSpriteFrameName("heart.png");
        energy->setPosition(ccp(size.width*10/80+i*size.width*12.7/240, size.height*2100/2200+winDif*4*(2-alpha)));
        addChild(energy,10000,41+i);
    }
    
    //7.体力回复时间
    if (MainUser->energyNumber < 5) {
        string nextRecoveryTimStr = int2string(nextRecoverySecond/60) + ":" + int2string(nextRecoverySecond%60);
        CCLabelTTF* recoveryTime = CCLabelTTF::create(nextRecoveryTimStr.c_str(), "Arial Rounded MT Bold", 24,CCSizeMake(size.width/3, 0),kCCTextAlignmentRight);
        recoveryTime->setPosition(ccp(size.width*20/80,size.height*2100/2200+winDif*4*(2-alpha)));
        addChild(recoveryTime,10000,46);
        
        schedule(schedule_selector(RankScene::energyTimeCounter), 1);
    }

    //5.关闭提示框
    MessageBox->closeMessageBox();
    
    //6.下一个动作
    if (tableIndex == 1) //如果之前就是排行榜,则直接把信息写上去
        rankListContent();
    else if(tableIndex == 2)//如果之前是题包列表,则旋转
        goToRankList();
}
예제 #21
0
void SGHttpClient::requestFinishHandler(CCNode *sender, void *data)
{
    CCHttpResponse *response = (CCHttpResponse*)data;
    
    if (!response)
    {
        return;
    }
    
    int statusCode = response->getResponseCode();
    CCLog("response code: %d", statusCode);
    if (!response->isSucceed())
    {
        SGMainManager::shareMain()->getMainScene()->plat->removeConnection();
		//        弹框
        if (_delegate)
        {
            _delegate->requestFailed();
        }
        CCLog("response failed");
        CCLog("error buffer: %s", response->getErrorBuffer());
        return;
    }
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        const char *responseTag = response->getHttpRequest()->getTag();
        CCLog("%s completed", responseTag);
        
        int rt = atoi(responseTag);
        std::vector<char> *buffer = response->getResponseData();
        int bufferSize = buffer->size();
        char *bufferchar = new char[bufferSize];
        std::copy(buffer->begin(), buffer->end(), bufferchar);
		
        switch (rt)
        {
            case MSG_HTTP_FAST_LOGIN:
            {
                this->fastLoginListener(bufferchar);
                break;
            }
            case MSG_HTTP_LOGIN:
            {
                this->loginListener(bufferchar);
                break;
            }
            case MSG_HTTP_REGISTER:
            {
                this->registerListener(bufferchar);
                break;
            }
            case MSg_HTTP_SERVERLIST:
            {
                this->serverListListener(bufferchar);
                break;
            }
            case MSG_HTTP_BING:
            {
                bindListener(bufferchar);
                break;
            }
            case MSG_HTTP_PASSWORD:
            {
                passwordListener(bufferchar);
                break;
            }
            case MSg_HTTP_LASTESTSERVER:
            {
                getlastestServer(bufferchar);
                break;
            }
            case MSG_HTTP_UPDATE_SERVER_STATE:
            {
                updateSelectServerResponse(bufferchar);
            }
                break;
            case MSG_HTTP_GET_CHANNEL_USER_ID:
            {
                rspGetChannelUserId(bufferchar);
            }
                break;
            default:
                break;
        }
		
    }
    CCUserDefault::sharedUserDefault()->setBoolForKey("pvp_tran", false);
    SGMainManager::shareMain()->getMainScene()->plat->removeConnection();
	
}
예제 #22
0
void LoadingScene::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
    CCLog("LoadingScene::onHttpRequestCompleted");
    CCHttpResponse *response = (CCHttpResponse*)data;
    
    if (!response)
    {
        return;
    }
    
    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    //m_labelStatusCode->setString(statusString);
    CCLog("response code: %d", statusCode);
    
    if (!response->isSucceed())
    {
        CCLog("response failed");
        CCLog("error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // dump data
    std::vector<char> *buffer = response->getResponseData();
	std::string s;
    bool isDataStarted = false;
    for (unsigned int i = 0; i < buffer->size(); i++)
	{
        if( isDataStarted == false && !isspace((*buffer)[i]) )
            isDataStarted = true;
        if( isDataStarted == false) continue;
        
        s += (*buffer)[i];
    }
	CCLog("LoadingScene::onHttpRequestCompleted : buffer=%s", s.data() );
    
    if(strcmp(response->getHttpRequest()->getTag(), "URL_RECEIVE_ANIMALS") == 0)
    {
        labelLoading->setString("동물들과 교감하는중...");
        vector<ANIMALINFO> animalList;
        
        CCLog("URL_RECEIVE_ANIMALS: it comes %d", s.length());
        
        bool isAlreadyExist = false;
        map<int, Animal*>* pList = pData->getAnimalsByAccount(SceneManager::sharedSceneManager()->getUserAccountKey());
        if( pList != NULL )
            isAlreadyExist = true;
        while (s.length() != 0)
        {
            int delimIndex = s.find('|');
            string oneAnimalData;
            
            if( delimIndex != -1 )
            {
                oneAnimalData = s.substr(0, delimIndex);
                s = s.substr(delimIndex+1);
            }
            else
            {
                oneAnimalData = s;
                s = "";
            }
            
            ANIMALINFO info;
            info.name               = oneAnimalData.substr(0, oneAnimalData.find(" ") );
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.key                = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.type               = (ANIMAL_TYPE)atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.level              = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.status.sleep       = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.status.poop        = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.status.exp         = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.status.fullness    = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.status.health      = atoi(oneAnimalData.substr(0, oneAnimalData.find(" ") ).data());
            oneAnimalData = oneAnimalData.substr(oneAnimalData.find(" ")+1);
            info.status.joy         = atoi(oneAnimalData.data());
            
            CCLog("URL_RECEIVE_ANIMALS : %s %d %d %d %d %d %d %d %d %d", info.name.c_str(), info.key, info.type, info.level, info.status.sleep, info.status.poop, info.status.exp, info.status.fullness, info.status.health, info.status.joy );
            
            pData->makeDataFromAnimalInfo(SceneManager::sharedSceneManager()->getHostAccountKey(), info);
            //            char name[32] = "께이";
            //            char strMB[256] = {0,};
            //            wchar_t strUnicode[256] = {0,};
            //            memcpy(strUnicode, info.name.data(), info.name.size());
            //            wcstombs(strMB, info.name.data(), 256);
            //
            //
            //            for(int i = 0; i < info.name.size(); i++ )
            //            {
            //                CCLog("URL_RECEIVE_ANIMALS : name %d, %d, %d", name[i], strUnicode[i], strMB[i] );
            //            }
            
        }
        
        if( SceneManager::sharedSceneManager()->isFriendHome() )
        {
            InGameScene* pInGameLayer = ((InGameScene*)InGameScene::getInGameScene()->getChildByTag(INGAME));
            pInGameLayer->resetScene(SceneManager::sharedSceneManager()->getHostAccountKey());
            CCDirector::sharedDirector()->popScene();
        }
        else
        {
            if( isAlreadyExist )
            {
                CCDirector::sharedDirector()->popScene();
                CCScene* pScene = InGameScene::getInGameScene();
                ((InGameScene*)(pScene->getChildByTag(INGAME)))->resetScene(SceneManager::sharedSceneManager()->getUserAccountKey());
            }
            else
                CCDirector::sharedDirector()->replaceScene(InGameScene::scene());
        }
    }
}
예제 #23
0
void EziFacebookFriend::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    
    if (!response)
    {
        CCLOG("[EziSocial Error]: No Response");
    }
    
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        //CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    
    if (!response->isSucceed())
    {
        CCLog("[EziSocial Error]: response failed");
        CCLog("[EziSocial Error]: error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // Dump the data
    std::vector<char> *buffer = response->getResponseData();
    
    // Create the CCSprite from data dump...
    
    CCImage * img=new CCImage();
    img->initWithImageData(&(buffer->front()), buffer->size());
    
    // Save file for resue.
    std::string writablePath = CCFileUtils::sharedFileUtils()->getWritablePath();
    //writablePath.append(response->getHttpRequest()->getTag());
    
    std::string fileName = "";
    fileName = fileName.append(_fbID);
    fileName = fileName.append(".jpg");
    writablePath.append(fileName);
    
    //CCLOG("File Name = %s", fileName.c_str());
    
    //CCLOG("File Path = %s", writablePath.c_str());
    
    cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D();
    texture->initWithImage(img);
    
    if(texture)
    {
        _profilePic = cocos2d::CCSprite::createWithTexture(texture);
    }
    else
    {
        CCLOGERROR("[EziSocial Error]: Cannot create user profile pic from texture.");
    }
    
    img->saveToFile(writablePath.c_str());
    delete img;
    
    if (_target && _selector)
    {
        (_target->*_selector)(_profilePic, _fbID.c_str());
    }
}
예제 #24
0
void XMLHttpRequest::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data){
    readyState = 4;
    
    CCHttpResponse *response = (CCHttpResponse *)data;
    if (!response) {
        return;
    }
    
    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    
    status = statusCode; //http status 
    
    if (!response->isSucceed())
    {
        CCLog("response failed");
        CCLog("error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // dump data
    std::string res;
    std::vector<char> *buffer = response->getResponseData();
    
    for (unsigned int i = 0; i < buffer->size(); i++)
    {
        res += ((*buffer)[i]);
    }
    
//    std::string res;
//    std::vector<char> *buffer = response->getResponseData();
//    res.clear();
//    res.assign((*buffer).begin(), (*buffer).end());
    
    responseText = res;
    

    JSBool hasAction;
    jsval temp_retval;
    
    do{
    if (JS_HasProperty(ScriptingCore::getInstance()->getGlobalContext(), ScriptingCore::getInstance()->getGlobalObject(), "onreadystatechange", &hasAction) && hasAction) {
        if(!JS_GetProperty(ScriptingCore::getInstance()->getGlobalContext(), ScriptingCore::getInstance()->getGlobalObject(), "onreadystatechange", &temp_retval)) {
            break;
        }
        if(temp_retval == JSVAL_VOID) {
            break;
        }
                
        jsval jsret;
        
        JS_CallFunctionName(ScriptingCore::getInstance()->getGlobalContext(), ScriptingCore::getInstance()->getGlobalObject(), "onreadystatechange", 0, NULL, &jsret);
    }

    }while(0);
//    jsval *retval;
//    JS_CallFunctionName(ScriptingCore::getInstance()->getGlobalContext(),
//                        ScriptingCore::getInstance()->getGlobalObject(),
//                        "onreadystatechange", NULL, NULL, retval);
}
예제 #25
0
void RankingScene::onHttpRequestCompleted(CCNode *sender, void *data) {
    CCHttpResponse *response = (CCHttpResponse*)data;
    
    if (!response)
    {
        return;
    }

    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    char statusString[64] = {0};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode,
            response->getHttpRequest()->getTag());
    
    if (!response->isSucceed())
    {
        CCLabelTTF *notConnectLabel =
        CCLabelTTF::create("Can't load Data", "BankGothic Md BT", 20);
        notConnectLabel->setPosition(ccp(w/2, h/2));
        this->addChild(notConnectLabel);
        return;
    }
    
    // dump data
    std::vector<char> *buffer = response->getResponseData();
    char * data2 = (char*)(malloc(buffer->size() *  sizeof(char)));
    int d = -1;
    printf("Http Test, dump data: ");
    for (unsigned int i = 0; i < buffer->size(); i++)
    {
        d++ ;
        data2[d] = (*buffer)[i];
    }
    data2[d + 1] = '\0';
    //-----------------------

    rapidjson::Document document;
    if(data2 != NULL && !document.Parse<0>(data2).HasParseError())
    {   
        for (rapidjson::SizeType  i = 0; i < document.Size(); i++)
        {
            Player *player = new Player(document[i]["name"].GetString(),
                                        document[i]["point"].GetInt());
            players->addObject(player);
        }
    } else {
        CCLog(document.GetParseError());
    }
    d = -1;
    CCTableView *tableView=CCTableView::create(this, CCSizeMake(700, 350));
    tableView->setDirection(kCCScrollViewDirectionVertical);
    tableView->setAnchorPoint(ccp(0, 0));
    tableView->setPosition(ccp(size.width/8, 250));
    tableView->setDelegate(this);
    tableView->setVerticalFillOrder(kCCTableViewFillTopDown);
    this->addChild(tableView, 21);
    tableView->reloadData();
}