使用CCHttpClient进行cocos2d-x网络编程
来源:互联网 发布:淘宝触屏版登录 编辑:程序博客网 时间:2024/05/18 18:14
From: http://blog.csdn.net/fansongy/article/details/9207595
首先创建一个cocos2d-x项目。
然后我创建了一个网络连接的类,名叫HttpNetConn。其继承自CCObject,管理网络连接的相应功能。
- /*
- * 网络连接模块
- * NetConnect.h
- *
- * Created by fansy [2013-6-30]
- */
- #ifndef _NET_CONNECTION_H_
- #define _NET_CONNECTION_H_
- #include <cocos2d.h>
- USING_NS_CC;
- class NetConnect: public CCObject
- {
- public:
- CREATE_FUNC(NetConnect);
- virtual bool init();
- void getData();
- void httpReqFinished(CCNode* node,CCObject* obj);
- };
- #endif
其中,getData()是向服务器发请求,httpReqFinished是服务器响应的应答。
好,接下来,动手实现。
首先,CCHttpClient在extition中,如果你的包含目录和我一样,没有这个,就要在项目属性->c/c++->附加包含目录中添加:$(SolutionDir)\extensions 此项(具体位置可能和我的有些不一样)。并在其NetConnection.cpp的头文件处加上:
- #include "cocos-ext.h"
- #include "../extensions/network/HttpClient.h"
- #include "../extensions/network/HttpRequest.h"
- USING_NS_CC_EXT;
接下来,写getData函数:
- void NetConnect::getData()
- {
- CCHttpClient* httpClient = CCHttpClient::getInstance();
- CCHttpRequest* httpReq =new CCHttpRequest();
- httpReq->setRequestType(CCHttpRequest::kHttpGet);
- httpReq->setUrl("http://www.baidu.com");
- httpReq->setResponseCallback(this,callfuncND_selector(NetConnect::httpReqFinished));
- httpReq->setTag("FirstNet");
- httpClient->setTimeoutForConnect(30);
- httpClient->send(httpReq);
- httpReq->release();
- }
觉得逻辑很清晰,就不细解释了。然后是回调函数:
- void NetConnect::httpReqFinished( CCNode* node,CCObject* obj )
- {
- CCHttpResponse* response = (CCHttpResponse*)obj;
- if (!response->isSucceed())
- {
- CCLog("Receive Error! %s\n",response->getErrorBuffer());
- return ;
- }
- const char* tag = response->getHttpRequest()->getTag();
- if ( 0 == strcmp("FirstNet",tag))
- {
- std::vector<char> *data = response->getResponseData();
- int data_length = data->size();
- std::string res;
- for (int i = 0;i<data_length;++i)
- {
- res+=(*data)[i];
- }
- res+='\0';
- CCLog("%s",res.c_str());
- }
- }
ok,F7编译。发现缺少库:
- 1> NetConnect.cpp
- 1>NetConnect.obj : error LNK2019: 无法解析的外部符号 "public: static class cocos2d::extension::CCHttpClient * __cdecl cocos2d::extension::CCHttpClient::getInstance(void)" (?getInstance@CCHttpClient@extension@cocos2d@@SAPAV123@XZ),该符号在函数 "public: void __thiscall NetConnect::getData(void)" (?getData@NetConnect@@QAEXXZ) 中被引用
- 1>NetConnect.obj : error LNK2019: 无法解析的外部符号 "public: void __thiscall cocos2d::extension::CCHttpClient::send(class cocos2d::extension::CCHttpRequest *)" (?send@CCHttpClient@extension@cocos2d@@QAEXPAVCCHttpRequest@23@@Z),该符号在函数 "public: void __thiscall NetConnect::getData(void)" (?getData@NetConnect@@QAEXXZ) 中被引用
- 1>D:\Code\UseLess\HelloCSDN\Debug.win32\HelloCSDN.win32.exe : fatal error LNK1120: 2 个无法解析的外部命令
缺少libExtensions.lib库,加上。在项目属性->链接器->附加依赖项中添加:libExtensions.lib。再编译。
额...似乎还缺:
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_create,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_detach,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_exit,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_mutex_init,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_mutex_destroy,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_mutex_lock,该符号在函数 "private: void __thiscall cocos2d::extension::CCHttpClient::dispatchResponseCallbacks(float)" (?dispatchResponseCallbacks@CCHttpClient@extension@cocos2d@@AAEXM@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_mutex_unlock,该符号在函数 "private: void __thiscall cocos2d::extension::CCHttpClient::dispatchResponseCallbacks(float)" (?dispatchResponseCallbacks@CCHttpClient@extension@cocos2d@@AAEXM@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_init,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_destroy,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_wait,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_post,该符号在函数 "private: virtual __thiscall cocos2d::extension::CCHttpClient::~CCHttpClient(void)" (??1CCHttpClient@extension@cocos2d@@EAE@XZ) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_slist_append,该符号在函数 "int __cdecl cocos2d::extension::processGetTask(class cocos2d::extension::CCHttpRequest *,unsigned int (__cdecl*)(void *,unsigned int,unsigned int,void *),void *,int *)" (?processGetTask@extension@cocos2d@@YAHPAVCCHttpRequest@12@P6AIPAXII1@Z1PAH@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_slist_free_all,该符号在函数 "int __cdecl cocos2d::extension::processGetTask(class cocos2d::extension::CCHttpRequest *,unsigned int (__cdecl*)(void *,unsigned int,unsigned int,void *),void *,int *)" (?processGetTask@extension@cocos2d@@YAHPAVCCHttpRequest@12@P6AIPAXII1@Z1PAH@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_easy_init,该符号在函数 "int __cdecl cocos2d::extension::processGetTask(class cocos2d::extension::CCHttpRequest *,unsigned int (__cdecl*)(void *,unsigned int,unsigned int,void *),void *,int *)" (?processGetTask@extension@cocos2d@@YAHPAVCCHttpRequest@12@P6AIPAXII1@Z1PAH@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_easy_setopt,该符号在函数 "bool __cdecl cocos2d::extension::configureCURL(void *)" (?configureCURL@extension@cocos2d@@YA_NPAX@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_easy_perform,该符号在函数 "int __cdecl cocos2d::extension::processGetTask(class cocos2d::extension::CCHttpRequest *,unsigned int (__cdecl*)(void *,unsigned int,unsigned int,void *),void *,int *)" (?processGetTask@extension@cocos2d@@YAHPAVCCHttpRequest@12@P6AIPAXII1@Z1PAH@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_easy_cleanup,该符号在函数 "int __cdecl cocos2d::extension::processGetTask(class cocos2d::extension::CCHttpRequest *,unsigned int (__cdecl*)(void *,unsigned int,unsigned int,void *),void *,int *)" (?processGetTask@extension@cocos2d@@YAHPAVCCHttpRequest@12@P6AIPAXII1@Z1PAH@Z) 中被引用
- 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_easy_getinfo,该符号在函数 "int __cdecl cocos2d::extension::processGetTask(class cocos2d::extension::CCHttpRequest *,unsigned int (__cdecl*)(void *,unsigned int,unsigned int,void *),void *,int *)" (?processGetTask@extension@cocos2d@@YAHPAVCCHttpRequest@12@P6AIPAXII1@Z1PAH@Z) 中被引用
再按之前的方法加入:libcurl_imp.lib、pthreadVCE2.lib 这两个库。再编译,走你。
终于行了。
接下来把它加到程序中。先在HelloWorldScene中加入NetConnect.h头文件。我更改了右下角的那个CCMenuItem的响应。
- void HelloWorld::menuCloseCallback(CCObject* pSender)
- {
- // "close" menu item clicked
- //CCDirector::sharedDirector()->end();
- NetConnect* nc = NetConnect::create();
- nc->getData();
- }
运行程序,点击右下角的按钮。看输出日志。打出了我们想要的东西。
=========================================================================
以下内容为本人在win7 64位 + vs2012 + cocos2d-x-3.2下的实践版本
先声明下:这个项目需要用到libNetwork.lib库,但是这个文件默认不存在,但是有相应的库项目,添加进来即可(路径:cocos2d\cocos\network\proj.win32\libNetwork.vcxproj),如图:
NetConnect.h
#ifndef __NET_CONNECT_H__#define __NET_CONNECT_H__#pragma once#include <cocos2d.h>USING_NS_CC;class NetConnect : public CCObject{public:CREATE_FUNC(NetConnect); virtual bool init();void getData();void httpReqFinished(CCNode* node, void* obj);};#endif
NetConnect.cpp
#include <cocos/network/HttpClient.h>#include <cocos/network/HttpRequest.h>#include "NetConnect.h"using namespace network;void writeFile(const char* fname, const std::string &str){FILE *fp = fopen(fname, "wb");if(fp){fwrite(str.c_str(), str.size(), 1, fp);fclose(fp);CCLog("write file successful");}elseCCLog("can not open file for write");}bool NetConnect::init(){return true;}void NetConnect::getData(){HttpClient* httpClient = HttpClient::getInstance();HttpRequest* httpReq = new HttpRequest();httpReq->setRequestType(HttpRequest::Type::GET);httpReq->setUrl("http://www.baidu.com");httpReq->setResponseCallback(this, callfuncND_selector(NetConnect::httpReqFinished));httpReq->setTag("FirstNet");httpClient->setTimeoutForConnect(30);httpClient->send(httpReq);httpReq->release();}void NetConnect::httpReqFinished( CCNode* node, void* obj ){HttpResponse* response = (HttpResponse*)obj;if (!response->isSucceed()){CCLog("Receive Error! %s\n", response->getErrorBuffer());return ;}const char* tag = response->getHttpRequest()->getTag();if ( 0 == strcmp("FirstNet", tag)){std::vector<char> *data = response->getResponseData();int data_length = data->size();std::string res;for (int i = 0; i < data_length; ++i){res += (*data)[i];}res += '\0';CCLog("%s", res.c_str());writeFile("baidu.html", res);}}
同时修改HelloWorld::init(),使其调用我们建立的这个NetConnect类:
bool HelloWorld::init(){ ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = LabelTTF::create("Hi, JoeBlack", "Arial", 44); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); NetConnect *netConn = NetConnect::create();netConn->getData(); return true;}
项目库的依赖关系如下图:
解决方案配置,可加快编译速度,参考:http://blog.csdn.net/peoplezhou/article/details/39957265
项目的头文件include路径添加"..\cocos2d",因为编译时的当前目录为解决方案(即*.sln)所在路径
再手工添加一个依赖库文件:libcurl_imp.lib,如图:
编译运行(F5或Ctrl+F5)后,将会在"Resources"下生成一个baidu.html文件(同时也说明程序运行时当前路径是Resources),双击该文件即可看到相应网页,也可通过编辑器查看其文本。
- 使用CCHttpClient进行cocos2d-x网络编程
- 使用CCHttpClient进行cocos2d-x网络编程
- 使用CCHttpClient进行cocos2d-x网络编程
- 使用CCHttpClient进行cocos2d-x网络编程
- 使用CCHttpClient进行cocos2d-x网络编程
- cocos2d-x CCHttpClient 访问网络
- Cocos2d-X中使用CCHttpClient实现网络通信
- Cocos2d-X中使用CCHttpClient实现网络通信
- [cocos2d-x]CCHttpClient的一个bug
- cocos2d-x-2.0.4的网络连接库CCHttpClient的BUG
- Cocos2d-X学习——CCHttpClient网络访问被防火墙拦截
- cocos2d-x网络编程
- cocos2d-x网络编程
- Cocos2d-x 网络编程
- cocos2d-x 利用cocos2d::extension::CCHttpClient 加载数据
- cocos2d-x 网络编程Curl
- 详解Cocos2d-x网络编程
- cocos2d-x 网络编程Curl
- Android开发环境相关问题记录
- Google和facebook如何应用R进行数据挖掘
- 二分查找算法(C++实现)
- 使用ltib
- 下拉放大效果
- 使用CCHttpClient进行cocos2d-x网络编程
- 黑马程序员------foundation字符串_NSString
- 蓝牙不能用了
- 关于java字节的问题,所以说明全在注释里面了,百分之百手敲,注意细节
- R语言学习由浅入深路线图
- HDU 1392 Surround the Trees 凸包的周长
- eclipse中maven配置
- R语言入门基础教程:常用运算函数
- 《剑指offer》面试题6重建二叉树