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());
	}
}

 

posted @ 2018-09-02 18:31  穆玄琅  阅读(329)  评论(0编辑  收藏  举报