cocos2dx与服务器交互

  1. #ifndef __HELLOWORLD_SCENE_H__

    #define __HELLOWORLD_SCENE_H__


    #include "cocos2d.h"

    #include "CResource.h"

    #include "cocos-ext.h"



    class HelloWorld : public cocos2d::CCLayer

    {

    public:

        // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone

        virtual bool init();  


        // there's no 'id' in cpp, so we recommend returning the class instance pointer

        static cocos2d::CCScene* scene();

        

        // implement the "static node()" method manually

        CREATE_FUNC(HelloWorld);

        

        RcMainScene m_rc;

        

        //menuItem添加到menu

        void addItemToMenu(cocos2d::CCMenu *menu, Stc_Node *node, cocos2d::SEL_MenuHandler handle = NULL);

        //点击menuItem回调函数

        void call_select(CCObject *pSender);

        

        //测试异步请求网络数据

        void testAsyNet();

        void call_asyNet(cocos2d::extension::CCHttpClient *sender, cocos2d::extension::CCHttpResponse *response);

    };


    #endif // __HELLOWORLD_SCENE_H__









#include "HelloWorldScene.h"

#include "CMessage.h"

#include "CCloud.h"

USING_NS_CC;

USING_NS_CC_EXT;



CCScene* HelloWorld::scene()

{

    // 'scene' is an autorelease object

    CCScene *scene = CCScene::create();

    

    // 'layer' is an autorelease object

    HelloWorld *layer = HelloWorld::create();


    // add layer as a child to scene

    scene->addChild(layer);


    // return the scene

    return scene;

}


// on "init" you need to initialize your instance

bool HelloWorld::init()

{

    //

    // 1. super init first

    if ( !CCLayer::init() )

    {

        return false;

    }


    //添加背景

    CCSprite *sprite = CCSprite::create(m_rc.m_bg.filename.c_str());

    sprite->setPosition(m_rc.m_bg.pos);

    this->addChild(sprite);


    //添加菜单

    CCMenu *cityMenu = CCMenu::create();

    cityMenu->setPosition(m_rc.m_cityMenu.pos);

    this->addChild(cityMenu);

   

    //添加按钮

    addItemToMenu(cityMenu, &m_rc.m_mine,       menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_shop,       menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_workShop,   menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_bar,        menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_chooseGenmenu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_train,      menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_trade,      menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_inherit,    menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_genMap,     menu_selector(HelloWorld::call_select));

    addItemToMenu(cityMenu, &m_rc.m_shrine,     menu_selector(HelloWorld::call_select));

    

    CCloud::create(this);

    

    return true;

}


//menuItem添加到menu

void HelloWorld::addItemToMenu(CCMenu *menu, Stc_Node *node, SEL_MenuHandler handler)

{

    CCMenuItemImage *item = CCMenuItemImage::create(node->filename.c_str(), node->filename.c_str());

    item->setTag(node->tag);

    item->setPosition(node->pos);

    if(handler)

    {

        item->setTarget(this, handler);

    }

    menu->addChild(item);

}


//点击menuItem回调函数

void HelloWorld::call_select(CCObject *pSender)

{

    CCMenuItemImage *item = dynamic_cast<CCMenuItemImage *>(pSender);

    CCAssert(item, "item不能为空, call_select");

    

    const char *cityName[10] = {"矿区", "商店", "玉石作坊", "酒馆", "点将台", "校场", "贸易中心", "传承塔", "名将图鉴", "战神殿"};

    

    int index = item->getTag() - 101;

    CCString *msg = CCString::createWithFormat("没有开启【%s,尽请期待!", cityName[index]);

  

    //CMessage::alert(this, msg->getCString());

    

    testAsyNet();

}




//测试请求网络数据

void HelloWorld::testAsyNet()

{

        CCHttpRequest *request = new CCHttpRequest();

        request->setUrl("http://www.phebe.cn/gallery/6/b2.jpg");

        request->setRequestType(CCHttpRequest::kHttpGet);

        request->setResponseCallback(this, (SEL_HttpResponse)(&HelloWorld::call_asyNet));

        request->setTag("PigGet");

    

        CCHttpClient::getInstance()->setTimeoutForConnect(30);

        CCHttpClient::getInstance()->send(request);

        request->release();

        request = NULL;

}



void HelloWorld::call_asyNet(cocos2d::extension::CCHttpClient *sender, cocos2d::extension::CCHttpResponse *response)

{

    //    判断是否响应成功

    if (!response->isSucceed())

    {

        CCString *str = CCString::createWithFormat("请求失败, %s\n",response->getErrorBuffer());

        CMessage::alert(this, str->getCString());

        return ;

    }

    

    const char* tag = response->getHttpRequest()->getTag();

    if (0 != strcmp("PigGet",tag))

    {

        return;

    }

        

    std::vector<char> *v = response->getResponseData();

    std::vector<char>::iterator itr = v->begin();

    //vector<char>转化为string

    std::string str;

    while (v->end() != itr) {

            

        str.append(1, *itr);

        ++itr;

    }

    

    

    CCString *strMsg = CCString::createWithFormat("成功从%s请求图片\n", tag);

    CMessage::alert(this, strMsg->getCString());

    

    std::string picName = std::string(tag) + ".png";

    std::string path = CCFileUtils::sharedFileUtils()->getWritablePath() + picName;

    std::string buff(v->begin(),v->end());

    

    //保存到本地文件

    FILE *fp = fopen(path.c_str(), "wb+");

    fwrite(buff.c_str(), 1, v->size(),  fp);

    fclose(fp);

    

}














  1. void TestLayer::btncallback( CCObject* pSender )  
  2. {  
  3.     bool requestType_is_get=true;//采用get方式或者post方式  
  4.     if (requestType_is_get)  
  5.     {  
  6.         CCHttpRequest* request = new CCHttpRequest();//创建请求对象  
  7.         string str1 = "127.0.0.1:80/index.html?";  
  8.         string str2 = p_User_EditBox->getText();//获取username编辑框内容  
  9.         string str3 = p_Psw_EditBox->getText();//获取password编辑框内容  
  10.         string struser="username=";  
  11.         string strpsw="&password=";  
  12.         str1=str1+struser+str2+strpsw+str3;  
  13.         request->setUrl(str1.c_str());//设置请求的url,username和password已经包含在url中  
  14.         request->setRequestType(CCHttpRequest::kHttpGet);//设置为Get模式  
  15.         request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//设置响应的回调  
  16.         request->setTag("GET test");  
  17.         CCHttpClient::getInstance()->send(request);//发送请求  
  18.         request->release();//释放请求  
  19.     }  
  20.     else  
  21.     {  
  22.         CCHttpRequest* request = new CCHttpRequest();//创建请求对象  
  23.         string str1 = "127.0.0.1:80/index.html";  
  24.         string str2 = p_User_EditBox->getText();  
  25.         string str3 = p_Psw_EditBox->getText();  
  26.         string struser="username=";  
  27.         string strpsw="&password=";  
  28.         str2=struser+str2+strpsw+str3;  
  29.   
  30.         request->setUrl(str1.c_str());//设置请求的url,只是请求页面的url,并不包含username和password  
  31.         request->setRequestType(CCHttpRequest::kHttpPost);//设置为Post模式  
  32.         request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//设置响应的回调  
  33.   
  34.         const char* postData = str2.c_str();  
  35.         request->setRequestData(postData, strlen(postData));//设置请求数据,也就是username和password  
  36.           
  37.         request->setTag("POST test");  
  38.         CCHttpClient::getInstance()->send(request);//发送请求  
  39.         request->release();//释放请求  
  40.     }  
  41. }  

4.2.响应回调处理

[cpp]  view plain copy
  1. void TestLayer::onHttpRequestCompleted( CCHttpClient* client, CCHttpResponse* response )  
  2. {  
  3.     if (!response->isSucceed())//如果响应失败,输出错误信息  
  4.     {    
  5.         CCString strError;  
  6.         strError.initWithFormat("Receive Error! \n%s\n",response->getErrorBuffer());  
  7.         m_labelStatusCode->setString(strError.getCString());  
  8.         return ;     
  9.     }    
  10.   
  11.     std::vector<char> *buffer = response->getResponseData();//接收响应信息  
  12.     string recieveData;  
  13.     for (unsigned int i = 0; i < buffer->size(); i++)  
  14.     {    
  15.         recieveData += (*buffer)[i];    
  16.     }  
  17.     size_t begin= recieveData.find("<body>")+6;//这里简单处理,获取<body>标签内数据,即是响应内容  
  18.     size_t end= recieveData.find("</body>");  
  19.     string result(recieveData,begin,end-begin);  
  20.     m_labelStatusCode->setString(result.c_str());  
  21. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值