使用CCHttpClient进行cocos2d-x网络编程

来源:互联网 发布:淘宝触屏版登录 编辑:程序博客网 时间:2024/05/18 18:14

From: http://blog.csdn.net/fansongy/article/details/9207595

在我使用的cocos2d-x版本(2.1.2)中,已经将curl融进cocos2d-x框架中。下面动手写个简单的网络程序。

   首先创建一个cocos2d-x项目。

    然后我创建了一个网络连接的类,名叫HttpNetConn。其继承自CCObject,管理网络连接的相应功能。

    

[cpp] view plaincopyprint?
  1. /* 
  2.  * 网络连接模块 
  3.  * NetConnect.h 
  4.  *  
  5.  * Created by fansy [2013-6-30] 
  6.  */  
  7.   
  8.   
  9. #ifndef _NET_CONNECTION_H_  
  10. #define _NET_CONNECTION_H_  
  11.   
  12. #include <cocos2d.h>  
  13.   
  14. USING_NS_CC;  
  15.   
  16. class NetConnect: public CCObject  
  17. {  
  18. public:  
  19.     CREATE_FUNC(NetConnect);  
  20.   
  21.     virtual bool init();  
  22.   
  23.     void getData();  
  24.   
  25.     void httpReqFinished(CCNode* node,CCObject* obj);  
  26.   
  27. };  
  28.   
  29.   
  30. #endif  

    其中,getData()是向服务器发请求,httpReqFinished是服务器响应的应答。

    好,接下来,动手实现。

    首先,CCHttpClient在extition中,如果你的包含目录和我一样,没有这个,就要在项目属性->c/c++->附加包含目录中添加:$(SolutionDir)\extensions 此项(具体位置可能和我的有些不一样)。并在其NetConnection.cpp的头文件处加上:

[cpp] view plaincopyprint?
  1. #include "cocos-ext.h"  
  2. #include "../extensions/network/HttpClient.h"  
  3. #include "../extensions/network/HttpRequest.h"  
  4.   
  5. USING_NS_CC_EXT;  

    接下来,写getData函数:

[cpp] view plaincopyprint?
  1. void NetConnect::getData()  
  2. {  
  3.     CCHttpClient* httpClient = CCHttpClient::getInstance();  
  4.   
  5.     CCHttpRequest* httpReq =new CCHttpRequest();  
  6.   
  7.     httpReq->setRequestType(CCHttpRequest::kHttpGet);  
  8.     httpReq->setUrl("http://www.baidu.com");  
  9.     httpReq->setResponseCallback(this,callfuncND_selector(NetConnect::httpReqFinished));  
  10.     httpReq->setTag("FirstNet");  
  11.     httpClient->setTimeoutForConnect(30);  
  12.     httpClient->send(httpReq);  
  13.   
  14.     httpReq->release();  
  15.   
  16. }  

    觉得逻辑很清晰,就不细解释了。然后是回调函数:

[cpp] view plaincopyprint?
  1. void NetConnect::httpReqFinished( CCNode* node,CCObject* obj )  
  2. {  
  3.     CCHttpResponse* response = (CCHttpResponse*)obj;  
  4.     if (!response->isSucceed())  
  5.     {  
  6.         CCLog("Receive Error! %s\n",response->getErrorBuffer());  
  7.         return ;   
  8.     }  
  9.   
  10.     const char* tag = response->getHttpRequest()->getTag();  
  11.     if ( 0 == strcmp("FirstNet",tag))  
  12.     {  
  13.         std::vector<char> *data = response->getResponseData();  
  14.         int data_length =  data->size();  
  15.         std::string res;  
  16.         for (int i = 0;i<data_length;++i)  
  17.         {  
  18.             res+=(*data)[i];  
  19.         }  
  20.         res+='\0';  
  21.         CCLog("%s",res.c_str());  
  22.     }  
  23. }  

    ok,F7编译。发现缺少库:

[plain] view plaincopyprint?
  1. 1>  NetConnect.cpp  
  2. 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) 中被引用  
  3. 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) 中被引用  
  4. 1>D:\Code\UseLess\HelloCSDN\Debug.win32\HelloCSDN.win32.exe : fatal error LNK1120: 2 个无法解析的外部命令  

   缺少libExtensions.lib库,加上。在项目属性->链接器->附加依赖项中添加:libExtensions.lib。再编译。

    额...似乎还缺:

[plain] view plaincopyprint?
  1. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_create,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用  
  2. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_detach,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用  
  3. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_exit,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用  
  4. 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) 中被引用  
  5. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__pthread_mutex_destroy,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用  
  6. 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) 中被引用  
  7. 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) 中被引用  
  8. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_init,该符号在函数 "private: bool __thiscall cocos2d::extension::CCHttpClient::lazyInitThreadSemphore(void)" (?lazyInitThreadSemphore@CCHttpClient@extension@cocos2d@@AAE_NXZ) 中被引用  
  9. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_destroy,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用  
  10. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_wait,该符号在函数 "void * __cdecl cocos2d::extension::networkThread(void *)" (?networkThread@extension@cocos2d@@YAPAXPAX@Z) 中被引用  
  11. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__sem_post,该符号在函数 "private: virtual __thiscall cocos2d::extension::CCHttpClient::~CCHttpClient(void)" (??1CCHttpClient@extension@cocos2d@@EAE@XZ) 中被引用  
  12. 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) 中被引用  
  13. 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) 中被引用  
  14. 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) 中被引用  
  15. 1>libExtensions.lib(HttpClient.obj) : error LNK2019: 无法解析的外部符号 __imp__curl_easy_setopt,该符号在函数 "bool __cdecl cocos2d::extension::configureCURL(void *)" (?configureCURL@extension@cocos2d@@YA_NPAX@Z) 中被引用  
  16. 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) 中被引用  
  17. 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) 中被引用  
  18. 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的响应。

[cpp] view plaincopyprint?
  1. void HelloWorld::menuCloseCallback(CCObject* pSender)  
  2. {  
  3.     // "close" menu item clicked  
  4.     //CCDirector::sharedDirector()->end();  
  5.     NetConnect* nc = NetConnect::create();  
  6.     nc->getData();  
  7. }  

    运行程序,点击右下角的按钮。看输出日志。打出了我们想要的东西。



=========================================================================

以下内容为本人在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),双击该文件即可看到相应网页,也可通过编辑器查看其文本。


0 0
原创粉丝点击