这里使用mysql数据库存储用户信息,使用php连接查询数据库,并将结果返回,c++端使用GET或POST的方式发送数据,获取服务器端的数据库分析,是否成功登陆!client端使用cocos2dx 的HTTPCLIENT类,服务器端使用 PHP + MYSQL +APACHE的环境。
后端PHP代码:
checkUserInfo.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$us=$_REQUEST["name"];
$ps=$_REQUEST["password"];
$conn=mysql_connect("localhost","root","root123456");
if(!$conn){
die('connect mysql false'.mysql_error());
}
//echo "connect mysql sucessfull <br>";
//open database
mysql_select_db("testphp");
//select userinfo
$sql = "select * from user where name ='".$us."' and password ='".$ps."';";
//execute sql
$result = mysql_query($sql);
$n = mysql_num_rows($result);
mysql_close($conn);
if($n>0){
session_start();
$row = mysql_fetch_array($result);
//var_dump($row);
echo "Login Success";
}
else{
echo "Login Failed";
}
mysql数据库信息:testphp库里有一张user表,里面有一条记录:name=hello,password=world
mysql> use testphp
Database changed
mysql> show tables;
+-------------------+
| Tables_in_testphp |
+-------------------+
| user |
+-------------------+
1 row in set (0.00 sec)
mysql> select *from user where name="hello" and password = "world";
+-------+----------+
| name | password |
+-------+----------+
| hello | world |
+-------+----------+
1 row in set (0.00 sec)
客户端使用 HloginGame.h" 和HloginGame.cpp" 来验证用户的登陆。
HloginGame.h"代码实现:
#ifndef __HloginGame__HloginGame__
#define __HloginGame__HloginGame__
#include "cocos2d.h"
#include "extensions/cocos-ext.h"
// HTTP
#include "network/HttpClient.h"
#include "network/HttpRequest.h"
#include "network/HttpResponse.h"
USING_NS_CC;
USING_NS_CC_EXT;
using namespace cocos2d::network;
class HloginGame : public cocos2d::Layer
{
public:
virtual bool init();
static cocos2d::Scene* createScene();
CREATE_FUNC(HloginGame);
EditBox* p_User_EditBox;
EditBox* p_Psw_EditBox;
LabelTTF* m_labelStatusCode;
void btncallback(Ref* pSender);
void onHttpRequestCompleted(HttpClient* client, HttpResponse* response);
void running(float dt);
int r;
//
void onExit();
void onEnterTransitionDidFinish();
};
#endif
HloginGame.cpp 代码实现:
#include "HloginGame.h"
#include "Hloading.h"
#include "HMenu.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
using namespace CocosDenshion;
Scene* HloginGame::createScene()
{
auto scene = Scene::create();
auto layer = HloginGame::create();
scene->addChild(layer);
return scene;
}
bool HloginGame::init()
{
if (!Layer::init())
{
return false;
}
Size size = Director::getInstance()->getVisibleSize();
//username
p_User_EditBox = EditBox::create(CCSizeMake(250, 50), Scale9Sprite::create("login_edit_normal.9.png"));
p_User_EditBox->setPosition(Vec2(size.width / 2 , size.height * 3 / 4));
p_User_EditBox->setFontColor(Color3B(0,255,0));
p_User_EditBox->setPlaceHolder("Username");
p_User_EditBox->setMaxLength(12);
p_User_EditBox->setInputMode(cocos2d::ui::EditBox::InputMode::SINGLE_LINE);
p_User_EditBox->setReturnType(cocos2d::ui::EditBox::KeyboardReturnType::DONE);
addChild(p_User_EditBox);
//password
p_Psw_EditBox = EditBox::create(CCSizeMake(250, 50), Scale9Sprite::create("login_edit_normal.9.png"));
p_Psw_EditBox->setPosition(Vec2(size.width / 2 , size.height / 2 + 100));
p_Psw_EditBox->setFontColor(Color3B(0, 255, 0));
p_Psw_EditBox->setPlaceHolder("Password");
p_Psw_EditBox->setMaxLength(12);
p_Psw_EditBox->setInputMode(cocos2d::ui::EditBox::InputMode::NUMERIC);
p_Psw_EditBox->setInputFlag(cocos2d::ui::EditBox::InputFlag::PASSWORD);
p_Psw_EditBox->setReturnType(cocos2d::ui::EditBox::KeyboardReturnType::DONE);
addChild(p_Psw_EditBox);
Scale9Sprite* confirmnormal = Scale9Sprite::create("btn_style_alert_dialog_button_normal.9.png");
confirmnormal->setContentSize(CCSizeMake(100, 60));
Scale9Sprite* confirmpressd = Scale9Sprite::create("btn_style_alert_dialog_button_pressed.9.png");
confirmpressd->setContentSize(CCSizeMake(100, 60));
MenuItemSprite* menuitem = MenuItemSprite::create(confirmnormal, confirmpressd, CC_CALLBACK_1(HloginGame::btncallback,this));
Menu* menu = CCMenu::create(menuitem, NULL);
menu->setPosition(size.width / 2 - 85, size.height / 4);
this->addChild(menu);
//
m_labelStatusCode = LabelTTF::create("HTTP Status Code", "Marker Felt", 20);
m_labelStatusCode->setAnchorPoint(Vec2(0, 0.5));
m_labelStatusCode->setPosition(Vec2(size.width / 2, size.height / 4));
m_labelStatusCode->setColor(Color3B(255, 0, 0));
addChild(m_labelStatusCode);
m_labelStatusCode->setString("waiting...");
return true;
}
void HloginGame::btncallback(Ref* pSender)
{
bool requestType_is_get = false;//get or post
if (requestType_is_get)
{
HttpRequest* request = new HttpRequest();// create requestObject
std::string str1 = "192.168.126.81/tst/checkUserInfo.php?";
std::string str2 = p_User_EditBox->getText();
std::string str3 = p_Psw_EditBox->getText();
std::string struser = "name=";
std::string strpsw = "&password=";
str1 = str1 + struser + str2 + strpsw + str3;
request->setUrl(str1.c_str());//set url
request->setRequestType(HttpRequest::Type::GET);//设置为Get模式
request->setResponseCallback(CC_CALLBACK_2(HloginGame::onHttpRequestCompleted,this));//设置响应的回调
request->setTag("GET test");
HttpClient::getInstance()->send(request);//send request
request->release();
}
else
{
HttpRequest* request = new HttpRequest();
std::string str1 = "192.168.126.81/tst/checkUserInfo.php";
std::string str2 = p_User_EditBox->getText();
std::string str3 = p_Psw_EditBox->getText();
std::string struser = "name=";
std::string strpsw = "&password=";
str2 = struser + str2 + strpsw + str3;
request->setUrl(str1.c_str());//url
request->setRequestType(HttpRequest::Type::POST);//设置为Post模式
request->setResponseCallback(CC_CALLBACK_2(HloginGame::onHttpRequestCompleted, this));// 设置响应的回调
const char* postData = str2.c_str();
request->setRequestData(postData, strlen(postData));//set userdata:usernamed and password
request->setTag("POST test");
HttpClient::getInstance()->send(request);//
request->release();//
}
}
void HloginGame::onHttpRequestCompleted(HttpClient* client, HttpResponse* response)
{
if (!response->isSucceed())
{
CCString strError;
strError.initWithFormat("Receive Error! \n%s\n", response->getErrorBuffer());
m_labelStatusCode->setString(strError.getCString());
return;
}
std::vector<char> *buffer = response->getResponseData();//
std::string recieveData;
for (unsigned int i = 0; i < buffer->size(); i++)
{
recieveData += (*buffer)[i];
}
std::string result = recieveData.c_str();
m_labelStatusCode->setString(result);
std::string::size_type idx = result.find("Success");
if (idx != std::string::npos)
{
//dely 2 sec running game
scheduleOnce(schedule_selector(HloginGame::running), 2);
}
}
void HloginGame::running(float dt)
{
cocos2d::Director::getInstance()->replaceScene(HMenu::createScene());
}
void HloginGame::onExit(){
Layer::onExit();
SimpleAudioEngine::getInstance()->stopBackgroundMusic();
}
void HloginGame::onEnterTransitionDidFinish(){
Layer::onEnterTransitionDidFinish();
SimpleAudioEngine::getInstance()->playBackgroundMusic("menuMusic.mp3", true);
}
运行的效果如下:
登陆成功,显示Login Success,然后跳转到游戏!
注意的问题:
1.client 发送的 关键字一定要和服务器端的关键字一致,这是一个容易忽略的问题,客户端使用username,服务器的关键字是name,就会出错!
2.对服务器端PHP返回的结果的处理:
std::vector<char> *buffer = response->getResponseData();//
std::string recieveData;
for (unsigned int i = 0; i < buffer->size(); i++)
{
recieveData += (*buffer)[i];
}