网络编程cocos2d-x里同样可以用两类网络通信方式:http和socket,http的主要用的是cURL,socket看上去要高端一些,用于更复杂的网络交互。
先写一个列子,看了列子就差不多了
1,首先头部引用
#include "stdio.h"
#include "stdlib.h"
#include "curl/curl.h"
2,头文件声明一个回调函数
static size_t httpWriteString(uint8_t* ptr,size_t size,size_t nmemb,voID *stream);
3,在init里面写
CURL *curl;
CURLcode res;
char buffer[10];
//初始化
curl = curl_easy_init();
//初始化OK后执行下面的代码
if (curl)
{
//这是链接数据返回时调用的数据接收回调函数
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,httpWriteString);
//这里设置的是当链接发生错误时终止运行
curl_easy_setopt(curl,CURLOPT_FAILONERROR,true);
//设置链接超时
curl_easy_setopt(curl,CURLOPT_TIMEOUT,10);
//设置http链接到百度首页
curl_easy_setopt(curl,CURLOPT_URL,"http://127.0.0.1:8088/gametest/index.PHP?a=asdfasdf&b=asdfsdf");
//执行链接后会返回一个curlCode,这个code有很多参数,0或者CURLE_OK表示链接成功,其它的就只好自己查阅了
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
if (res == CURLE_OK)
{
cclog("----------------------------------success--------------");
}
else
{
cclog("--------------------failure------------------------");
}
}
else
{
cclog("----------------------------------no curl-----------------");
}
4,实现回调函数
size_t HelloWorld::httpWriteString(uint8_t* ptr,size_t number,voID *stream)
{
cclog("%s",ptr);
return size*number;//这里一定要返回实际返回的字节数
}
这样就可以实现curl的弱联网技术了,这个事通过http请求的GET方式
——————————————————————————————第二个方法,这个还是好使的——————————————————————
.h文件里面的内容
#ifndef __LayerPaihan__#define __LayerPaihan__#include "cocos2d.h"#include "extensions/cocos-ext.h"#include "network/httpClIEnt.h"USING_NS_CC;USING_NS_CC_EXT;using namespace network;class LayerPaihan : public cocos2d::Layercolor{public: virtual bool init(); CREATE_FUNC(LayerPaihan); //屏蔽下面的触摸事件 EventListenertouchOneByOne * Listener; bool ontouchBegan(touch* touch,Event* event); voID menuClose(cocos2d::Ref* psender); voID menuCloseCallback(cocos2d::Ref* pSender); voID onMenuGetTestClicked(Ref* sender); voID onMenuPostBinaryTestClicked(Ref* sender); // http Response Callback voID onhttpRequestCompleted(cocos2d::network::httpClIEnt *sender,cocos2d::network::httpResponse *response); Sprite* bg;};#endif
.cpp里面的代码
#include "LayerPaihan.h"#include "Json\rAPIdJson.h"#include "Json\document.h"#include "Json\stringbuffer.h"using namespace rAPIdJson; bool LayerPaihan::init() { if(!Layercolor::initWithcolor(color4B(0,128))){ return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Listener = EventListenertouchOneByOne::create(); Listener->setSwallowtouches(true); Listener->ontouchBegan = CC_CALLBACK_2(LayerPaihan::ontouchBegan,this); _eventdispatcher->addEventListenerWithSceneGraPHPriority(Listener,this); bg = Sprite::create("ph_bg.jpg"); bg->setposition(Point(visibleSize.wIDth/2,visibleSize.height/2)); this->addChild(bg); const int margin = 40; const int SPACE = 70; auto menuRequest = Menu::create(); menuRequest->setposition(Point::ZERO); bg->addChild(menuRequest); httpRequest* request = new httpRequest(); request->setUrl("http://127.0.0.1:8088/game/index.PHP"); request->setRequestType(httpRequest::Type::GET); request->setResponseCallback(this,httpresponse_selector(LayerPaihan::onhttpRequestCompleted)); request->setTag("GET test1"); httpClIEnt::getInstance()->send(request); request->release(); auto close =MenuItemSprite::create(Sprite::createWithSpriteFramename("x.png"),Sprite::createWithSpriteFramename("x.png"),CC_CALLBACK_1(LayerPaihan::menuClose,this)); close->setposition(Point(bg->getContentSize().wIDth,bg->getContentSize().height)); auto menu = Menu::create(close,NulL); menu->setposition(Vec2::ZERO); bg->addChild(menu,6); return true; } bool LayerPaihan::ontouchBegan(touch* touch,Event* event){ return true; } voID LayerPaihan::menuClose(cocos2d::Ref* psender){ this->setVisible(false); Listener->setSwallowtouches(false); } voID LayerPaihan::onMenuGetTestClicked(Ref* sender){ httpRequest* request = new httpRequest(); request->setUrl("http://127.0.0.1:8088/game/index.PHP"); request->setRequestType(httpRequest::Type::GET); request->setResponseCallback(this,httpresponse_selector(LayerPaihan::onhttpRequestCompleted)); request->setTag("GET test1"); httpClIEnt::getInstance()->send(request); request->release();} voID LayerPaihan::onMenuPostBinaryTestClicked(cocos2d::Ref *sender){ httpRequest* request = new httpRequest(); request->setUrl("http://127.0.0.1:8088/game/index.PHP"); request->setRequestType(httpRequest::Type::POST); request->setResponseCallback(this,httpresponse_selector(LayerPaihan::onhttpRequestCompleted)); const char* postData = "params = Value"; request->setRequestData(postData,strlen(postData) ); request->setTag("POST test1"); httpClIEnt::getInstance()->send(request); request->release(); } voID LayerPaihan::onhttpRequestCompleted(cocos2d::network::httpClIEnt *sender,cocos2d::network::httpResponse *response){ if (!response) { return; } if (0 != strlen(response->gethttpRequest()->getTag())) { log("%s completed",response->gethttpRequest()->getTag()); } long statusCode = response->getResponseCode(); char statusstring[64] = {}; if (!response->isSucceed()) { log("response Failed"); log("error buffer: %s",response->getErrorBuffer()); return; } std::vector<char>* buffer = response->getResponseData(); std::stringstream oss; for(unsigned int i=0;i < buffer->size();i++){ oss<<(*buffer)[i]; } std::string temp=oss.str(); const char * buf=temp.c_str(); rAPIdJson::document doc; doc.Parse<0>(buf);//<通过Parse方法将Json数据解析出来 if(doc.HasParseError()) { cclOG("GetParseError%s\n",doc.GetParseError()); } if(doc.IsArray())///<判断是否是字符串 { for (unsigned int i = 0; i< doc.Size(); ++i) { const rAPIdJson::Value &index = doc[i]["index"]; const rAPIdJson::Value &name = doc[i]["name"]; const rAPIdJson::Value &gold = doc[i]["gold"]; auto xs = Label::createWithSystemFont(index.GetString(),"Microsoft YaHei",18); xs->setAnchorPoint(Point(0,0)); xs->setposition(Point(200,244-i*30)); bg->addChild(xs); auto xs_name = Label::createWithSystemFont(name.GetString(),18); xs_name->setAnchorPoint(Point(0,0)); xs_name->setposition(Point(310,244-i*30)); bg->addChild(xs_name); auto xs_gold = Label::createWithSystemFont(gold.GetString(),18); xs_gold->setAnchorPoint(Point(0,0)); xs_gold->setposition(Point(440,244-i*30)); bg->addChild(xs_gold); } }}
完了以后加载network模块,重新编译一下
这个倒是挺好事的
——————————————————————————————下面是官方的文档————————————————————————
我试了总是不成功,要是有搞明白 的请指教,先谢谢了
介绍httpClIEnt是http客户端的接口。httpClIEnt封装了各种对象,处理cookies,身份认证,连接管理等。
概念httpClIEnt的使用一般包含下面6个步骤:
创建 httpRequest 的实例;设置某种连接方法的类型(GET、POST等),这里通过setUrl传入待连接的地址;
设置响应回调函数,读取response;
添加请求到httpClIEnt任务队列; 释放连接。无论执行方法是否成功,都必须释放连接;
对得到后的内容进行处理。 如何使用 引入头文件和命名空间
#include "network/httpClIEnt.h"using namespace cocos2d::network;httpRequest 实例
我们将使用httpRequest无参数的构造函数,它为大多数情况提供了一个很好的默认设置,所以我们使用它。
httpRequest* request = new httpRequest();设置连接方法的类型和待连接的地址
由http规范定义的各种方法对应各种不同的httpRequest类。
我们将使用Get方法,这是一个简单的方法,它只是简单地取得一个URL,获取URL指向的文档。
request->setRequestType(httpRequest::Type::GET);request->setUrl("http://www.httpbin.org/get");设置回调
无论服务器返回怎样的状态,响应主体response body总是可读的,这至关重要。
request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onhttpComplete,this));
在onhttpComplete里读取响应数据:
std::vector<char> *buffer = response->getResponseData();//Get the request data pointer back添加请求到httpClIEnt任务队列
cocos2d::network::httpClIEnt::getInstance()->send(request);释放连接
这是一个可以让整个流程变得完整的关键步骤,我们必须告诉httpClIEnt,我们已经完成了连接,并且它现在可以重用。如果不这样做的话,httpClIEnt将无限期地等待一个连接释放,以便它可以重用。
要释放连接,使用:
request->release();处理响应
现在,我们已经完成了与httpClIEnt的交互,可以集中精力做我们需要处理的数据。在这个例子中,我们仅仅将它在控制台上输出。
// dump datastd::vector *buffer = response->getResponseData();printf("http Test,dump data: ");for (unsigned int i = 0; i < buffer->size(); i++){ printf("%c",(*buffer)[i]);}printf("\n");
如果你需要把response作为一个流来读取它里面的信息,上面的步骤将会同如何解析这个连接结合,当你处理完所有的数据后,关闭输入流,并释放该连接。
GET请求示例下面是一个通过httpClIEnt的http GET请求的例子。
httpRequest* request = new httpRequest(); request->setUrl("http://www.baIDu.com"); request->setRequestType(httpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onhttpRequestCompleted,this)); request->setTag("GET test"); cocos2d::network::httpClIEnt::getInstance()->send(request); request->release();POST请求示例
下面将发送一个POST请求到URL“http://httpbin.org/post”。
httpRequest* request = new httpRequest(); request->setUrl("http://httpbin.org/post"); request->setRequestType(httpRequest::Type::POST); request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onhttpRequestCompleted,this)); // write the post data const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; request->setRequestData(postData,strlen(postData)); request->setTag("POST test"); cocos2d::network::httpClIEnt::getInstance()->send(request); request->release();处理网络回调函数
voID HelloWorld::onhttpRequestCompleted(httpClIEnt *sender,httpResponse *response){ if (!response) { return; } // You can get original request type from: response->request->reqType if (0 != strlen(response->gethttpRequest()->getTag())) { log("%s completed",response->gethttpRequest()->getTag()); } int statusCode = response->getResponseCode(); char statusstring[64] = {}; sprintf(statusstring,"http Status Code: %d,tag = %s",statusCode,response->gethttpRequest()->getTag()); _labelStatusCode->setString(statusstring); log("response code: %d",statusCode); if (!response->isSucceed()) { log("response Failed"); log("error buffer: %s",response->getErrorBuffer()); return; } // dump data std::vector<char> *buffer = response->getResponseData(); printf("http Test,dump data: "); for (unsigned int i = 0; i < buffer->size(); i++) { printf("%c",(*buffer)[i]); } printf("\n");}AndroID
需要注意的是,如果你是AndroID环境,不要忘了在您的应用程序的Manifest 中增加相应的权限:
<uses-permission androID:name=”androID.permission.INTERNET” />
详细代码可参照..\tests\Cpp\TestCpp\Classes\ExtensionsTest\NetworkTest\httpClIEntTest.cpp
总结以上是内存溢出为你收集整理的cocos2d-x httpclient发送get或者post消息请求全部内容,希望文章能够帮你解决cocos2d-x httpclient发送get或者post消息请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)