网络编程 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 size,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
#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,0,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(),"Microsoft YaHei",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(),"Microsoft YaHei",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个步骤:
#include "network/HttpClient.h"
using namespace cocos2d::network;
我们将使用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
cocos2d::network::HttpClient::getInstance()->send(request);
这是一个可以让整个流程变得完整的关键步骤, 我们必须告诉HttpClient,我们已经完成了连接,并且它现在可以重用。如果不这样做的话,HttpClient将无限期地等待一个连接释放,以便它可以重用。
要释放连接,使用:
request->release();
现在,我们已经完成了与HttpClient的交互,可以集中精力做我们需要处理的数据。在这个例子中,我们仅仅将它在控制台上输出。
// dump data
std::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作为一个流来读取它里面的信息,上面的步骤将会同如何解析这个连接结合,当你处理完所有的数据后,关闭输入流,并释放该连接。
下面是一个通过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请求到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环境,不要忘了在您的应用程序的Manifest 中增加相应的权限:
<uses-permission android:name=”android.permission.INTERNET” />
详细代码可参照..\tests\Cpp\TestCpp\Classes\ExtensionsTest\NetworkTest\HttpClientTest.cpp