天天看點

Cocos2d-X多線程(4) 在子線程中進行網絡請求

新版本的android系統已經不允許在UI線程中進行網絡請求了,必須建立一個線程。

代碼實操:

頭檔案:

#ifndef __TestThreadHttp_SCENE_H__
#define __TestThreadHttp_SCENE_H__

#include "cocos2d.h"
#include "network\HttpRequest.h"
#include "network\HttpClient.h"
#include "network\HttpResponse.h"

USING_NS_CC;
using namespace cocos2d::network;

class TestThreadHttp : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();
    virtual bool init();
	CREATE_FUNC(TestThreadHttp);

	void theadA();
	void complete(HttpClient *client,HttpResponse *response); 
};

#endif // __TestThreadHttp_SCENE_H__
           

源檔案:

#include "TestThreadHttp.h"
#include <thread>

Scene* TestThreadHttp::createScene()
{
    auto scene = Scene::create();
    auto layer = TestThreadHttp::create();
    scene->addChild(layer);
    return scene;
}

bool TestThreadHttp::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

	std::thread t1(&TestThreadHttp::theadA,this);
	t1.detach();
    return true;
}
void TestThreadHttp::theadA()
{
	auto request = new HttpRequest();
	request->setUrl("http://httpbin.org/ip");
	request->setTag("type get");
	//設定請求類型
	request->setRequestType(HttpRequest::Type::GET);
	char data[50] = "data";
	request->setRequestData(data,strlen(data));
	request->setResponseCallback(CC_CALLBACK_2(TestThreadHttp::complete,this));
	//建立httpclinet對象
	auto client = HttpClient::getInstance();
	client->setTimeoutForConnect(60);
	client->setTimeoutForRead(100);
	client->send(request);
	request->release();
}


void TestThreadHttp::complete(HttpClient *client,HttpResponse *response)
{
	log("request tag is:%s",response->getHttpRequest()->getTag());
	log("response code is:%d",response->getResponseCode());
	if(response->isSucceed())
	{
		/*std::vector<char> * data = response->getResponseData();
		log("response data is:");
		for (int i = 0; i < data->size(); i++)
		{
			log("%c",(*data)[i]);
		}*/
		std::vector<char> * data = response->getResponseData();
		std::stringstream oss;
		for (int i = 0; i < data->size(); i++)
		{
			oss<<(*data)[i];
		}
		std::string str = oss.str();
		log("response data is:%s",str.c_str());

		//在場景中添加精靈
		auto sprite = Sprite::create("HelloWorld.png");
		addChild(sprite);
		Size size = Director::getInstance()->getWinSize();
		sprite->setPosition(size/2);
		
	}else
	{
		log("error msg is:%s",response->getErrorBuffer());
	}
}