Cocos2d-X中使用CCHttpClient实现网络通信
前端之家收集整理的这篇文章主要介绍了
Cocos2d-X中使用CCHttpClient实现网络通信,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在使用CCHttpClient前首先需要搭建一个Apache服务器
搭建Apache服务器和使用Apache服务器的方法可以参考下面的博客:
在Windows下搭建Apache服务器:http://blog.csdn.net/houjia159/article/details/43453325
开发基于Apache服务器上的CGI程序:http://blog.csdn.net/houjia159/article/details/43453351
一步一步教你使用CGI实现一个简单的后门:http://blog.csdn.net/houjia159/article/details/43453361
程序实例1:在Cocos2d-X中使用CCHttpClient实现登陆验证
使用VS2012编译下面的代码(服务器端的代码):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
//设置HTML语言
printf("Content-type:text/html\n\n");
//通过环境变量得到用户传递的参数
char* queryString = getenv("QUERY_STRING");
//分解字符串queryString
//将字符串queryString分割成两个字符串,'|'为分隔符
char* username = strtok(queryString,"|");
char* password = strtok(NULL,"|");
//判断用户名和密码是否输入正确
if(0 == strcmp(username,"aaa") && 0 == strcmp(password,"bbb"))
{
printf("Login success !<br>");
}
else
{
printf("Login Error !<br>");
}
}
编译成功后将程序复制到Apache服务器中
在浏览器中输入:http://localhost/cgi-bin/login.cgi?aaa|bbb
在浏览器中输入:http://localhost/cgi-bin/login.cgi?aaaa
通过上面的例子证明服务器端的程序编译成功,并且程序实现了一个简单的验证,当用户传递的参数是aaa|bbb时验证成功,当用户传递的参数不是aaa|bbb时验证失败
客服端的代码
当Cocos2d-X作为客服端执行这个程序时,首先创建一个HttpClient类,在HttpClient.h中添加下面的代码
using namespace cocos2d::extension;
USING_NS_CC;
class HttpClient : public CCLayer
{
public:
static CCScene* scene();
CREATE_FUNC(HttpClient);
bool init();
void httpResponse(CCHttpClient* client,CCHttpResponse* response);
};
在HttpClient.cpp中添加下面的代码
#include "HttpClient.h"
CCScene* HttpClient::scene()
{
CCScene* s = CCScene::create();
HttpClient* layer = HttpClient::create();
s->addChild(layer);
return s;
}
bool HttpClient::init()
{
CCLayer::init();
CCHttpClient* httpClient = CCHttpClient::getInstance();
CCHttpRequest* request = new CCHttpRequest;
request->setUrl("http://localhost/cgi-bin/login.cgi?aaa|bbb");
request->setResponseCallback(this,httpresponse_selector(HttpClient::httpResponse));
request->setRequestType(CCHttpRequest::kHttpGet);
httpClient->send(request);
request->release();
return true;
}
void HttpClient::httpResponse(CCHttpClient* client,CCHttpResponse* response)
{
if (!response->isSucceed())
{
const char* err = response->getErrorBuffer();
CCLog("response error = %s",err);
return;
}
std::vector<char>* vChar = response->getResponseData();
std::string str;
vector<char>::iterator it;
for (it = vChar->begin(); it != vChar->end(); it++)
{
str += *it;
}
CCLog("%s",str.c_str());
}
执行结果:
将HttpClient.cpp下的HttpClient::init()中的
//设置请求访问的地址
request->setUrl(<a target=_blank href="http://localhost/cgi-bin/login.cgi?aaa|bbb">http://localhost/cgi-bin/login.cgi?aaa|bbb</a>);
改成
后的执行结果:
程序实例2:在Cocos2d-X中使用CCHttpClient实现客服端向服务器发送数据服务器处理客服端的数据并且返回数据
使用VS2012编译下面的代码(服务器端的代码):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
printf("Content-type:text/html\n\n");
char* contentLength = getenv("CONTENT_LENGTH");
int length = atoi(contentLength);
printf("content length = %d<br>\n",length);
char* buf = (char*)malloc(length);
memset(buf,0,136); font-style:italic">//将stdin(缓冲区)中的数据读取到buf中
fread(buf,length,153)">1,stdin);
printf("%s<br>\n",buf);
free(buf);
}
客服端代码:
//获得网络共享实例
CCHttpClient* httpClient = CCHttpClient::getInstance();
CCHttpRequest* request = new CCHttpRequest;
request->setRequestType(CCHttpRequest::kHttpPost);
);
request->setResponseCallback(this,httpresponse_selector(HttpClient::httpResponse));
request->setRequestData("aaa|bbb|",153)">8);
httpClient->setTimeoutForConnect(30);
httpClient->send(request);
程序实例3:在Cocos2d-X中使用CCHttpClient实现一个简单的登录功能
服务器端代码:
使用VS2012编译下面的代码
//分解字符串queryString
char* username = strtok(buf,"|");
char* password = strtok(NULL,68)">"|");
if(0 == strcmp(username,68)">"aaa") && 0 == strcmp(password,68)">"bbb"))
{
printf("0");
}
else if(0 != strcmp(username,68)">"1");
}
else if(0 != strcmp(password,68)">"bbb"))
{
printf("2");
}
else
{
printf("3");
}
#define _Login_H_
#include "cocos2d.h"
#include "cocos-ext.h"
using namespace cocos2d::extension;
USING_NS_CC;
class Login : public CCLayer
{
public:
static CCScene* scene();
bool init();
CREATE_FUNC(Login);
void menuHandler(CCObject*);
void httpResponse(CCHttpClient* client,CCHttpResponse* response);
CCLabelTTF* label3;
CCLabelTTF* label4;
CCLabelTTF* label5;
char strName[256];
char strPassword[256];
CCEditBox* m_pEditName;
CCEditBox* m_pEditPassword;
};
endif
在Login.cpp中添加下面的代码
#include "Login.h"
CCScene* Login::scene()
{
static CCScene* scene = CCScene::create();
Login* layer = Login::create();
scene->addChild(layer);
return scene;
}
bool Login::init()
{
CCLayer::init();
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
char UserName[256];
char Password[//保存密码
char isUserName[//保存用户名的判断结果
char isPassword[//保存密码的判断结果
char Login[//保存登录结果
CCDictionary* dict = CCDictionary::createWithContentsOfFile("information.plist");
const CCString* username = dict->valueForKey("username");
sprintf(UserName,username->getCString());
const CCString* password = dict->valueForKey("password");
sprintf(Password,password->getCString());
const CCString* isusername = dict->valueForKey("isusername");
sprintf(isUserName,isusername->getCString());
const CCString* ispassword = dict->valueForKey("ispassword");
sprintf(isPassword,ispassword->getCString());
const CCString* login = dict->valueForKey("login");
sprintf(Login,login->getCString());
CCLabelTTF* label1 = CCLabelTTF::create(UserName,68)">"Arial",153)">25);
CCLabelTTF* label2 = CCLabelTTF::create(Password,153)">25);
label3 = CCLabelTTF::create(isUserName,153)">25);
label4 = CCLabelTTF::create(isPassword,153)">25);
label5 = CCLabelTTF::create(Login,153)">25);
addChild(label1);
addChild(label2);
addChild(label3);
addChild(label4);
addChild(label5);
label1->setPosition(ccp(winSize.width / 2 - 100,winSize.height / 2 + 100));
label2->setPosition(ccp(winSize.width / 60));
label3->setPosition(ccp(winSize.width / 2,153)">50));
label4->setPosition(ccp(winSize.width / 80));
label5->setPosition(ccp(winSize.width / 50));
label3->setVisible(false);
label4->setVisible(false);
label5->setVisible(false);
m_pEditName = CCEditBox::create(CCSizeMake(winSize.width / 3,153)">30),CCScale9Sprite::create("green_edit.png"));
m_pEditName->setPosition(ccp(winSize.width - 220,153)">100));
addChild(m_pEditName);
m_pEditName->setFontSize(10);
m_pEditName->setFontColor(ccBLACK);
m_pEditName->setPlaceholderFontColor(ccBLACK);
m_pEditName->setMaxLength(8);
m_pEditName->setReturnType(kKeyboardReturnTypeGo);
m_pEditName->setInputMode(kEditBoxInputModeAny);
m_pEditPassword = CCEditBox::create(CCSizeMake(winSize.width / "yellow_edit.png"));
m_pEditPassword->setPosition(ccp(winSize.width - 60));
addChild(m_pEditPassword);
m_pEditPassword->setFontColor(ccBLACK);
m_pEditPassword->setMaxLength(10);
m_pEditPassword->setInputFlag(kEditBoxInputFlagPassword);
m_pEditPassword->setInputMode(kEditBoxInputModeSingleLine);
CCMenu* menu = CCMenu::create();
addChild(menu);
CCMenuItemImage* LoginMenu = CCMenuItemImage::create("button.png",68)">"button.png");
menu->addChild(LoginMenu);
LoginMenu->setTarget(this,menu_selector(Login::menuHandler));
return true;
}
void Login::menuHandler(CCObject*)
{
sprintf(strName,m_pEditName->getText());
sprintf(strPassword,m_pEditPassword->getText());
char strSend[256];
sprintf(strSend,68)">"%s|%s",strName,strPassword);
CCHttpClient* httpClient = CCHttpClient::getInstance();
CCHttpRequest* request = new CCHttpRequest;
request->setRequestType(CCHttpRequest::kHttpPost);
request->setUrl("http://localhost/cgi-bin/login.cgi");
request->setResponseCallback(this,httpresponse_selector(Login::httpResponse));
request->setRequestData(strSend,sizeof(strSend));
httpClient->setTimeoutForConnect(30);
httpClient->send(request);
request->release();
}
void Login::httpResponse(CCHttpClient* client,CCHttpResponse* response)
{
if (!response->isSucceed())
{
const char* err = response->getErrorBuffer();
CCLog(
return;
}
vector<char>* vChar = response->getResponseData();
string str;
vector<char>::iterator it;
for (it = vChar->begin(); it != vChar->end(); it++)
{
str += *it;
}
CCLog(//将服务器传到客服端的数据转换成整型
int num = atoi(str.c_str());
switch(num)
{
case 0:
label5->setVisible(true);
break;
case 1:
label3->setVisible(true);
break;
case 2:
label4->setVisible(true);
break;
case 3:
label3->setVisible(true);
label4->setVisible(true);
break;
default:
break;
}
}
客服端实现的功能:
1、输入用户名和密码
2、将用户名和密码发送给服务器
3、接收服务器发送到客服端的数据
4、当接收的数据为0时,表示用户名和密码输入正确,在界面上显示”登录成功“
5、当接收的数据为1时,表示用户名错误,密码正确,在界面上显示”用户名错误“
6、当接收的数据为2时,表示用户名正确,密码错误,在界面上显示"密码错误"
4、当接收的数据为3时,表示用户名和密码都错误,在界面上显示”用户名错误“、”密码错误“
当在用户名中输入aaa,密码中输入bbb,后单击登录会显示登录成功
当在用户名中输入a,密码中输入bbb,后单击登录会显示用户名错误
当在用户名中输入aaa,密码中输入b,后单击登录会显示密码错误
当在用户名中输入a,密码中输入b,后单击登录会显示用户名错误、密码错误
原文链接:https://www.f2er.com/cocos2dx/344529.html