cocos2dx 实现连接登陆服务器认证后进入游戏

主要使用到的是cocos2dx封装的HTTPCLIENT类来连接服务器。服务器后端使用php来返回数据和client交互。UI控件EDITBOX的使用,scheduleOnce的延时调用!

认证过程:

1.客户端发送 username和password 给服务器端;

2.服务器核对用户名和密码(可以用数据库里的数据mysql,查询是否存在用户并比对user和password的值);

3.服务器返回给client端 信息

4.客户端根据服务器返回的信息,判断是否进入游戏和其他处理(可以做更多的处理,新建账号保存等)


具体代码:

客户端代码使用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 = true;//get or post
	if (requestType_is_get)
	{
		HttpRequest* request = new HttpRequest();// create requestObject
		std::string str1 = "192.168.126.81/tst/index.php?";
		std::string str2 = p_User_EditBox->getText();
		std::string str3 = p_Psw_EditBox->getText();
		std::string struser = "username=";
		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/index.php";
		std::string str2 = p_User_EditBox->getText();
		std::string str3 = p_Psw_EditBox->getText();
		std::string struser = "username=";
		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];
	}
	size_t begin = recieveData.find("<body>") + 6;
	size_t end = recieveData.find("</body>");

	std::string result(recieveData, begin, end - begin);

	m_labelStatusCode->setString(result.c_str());


	result = result.c_str();
	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);

}

服务器端使用php+apache的认证方式:

[root@iZbp18wsk0m120rjqyvthbZ tst]# cat index.php

<html>  
<body>  
<?php  
$open=fopen("./log.txt","a" ); //Save password  
if(isset($_REQUEST["username"]) && isset($_REQUEST["password"]))  
{  
    if($_REQUEST["username"] == "hello" && $_REQUEST["password"] == "world")  
        {  
        fwrite($open,"Username:".$_REQUEST["username"]);  
            fwrite($open,"\r\n");  
            fwrite($open,"Password:".$_REQUEST["password"]);  
        echo "Login Success"; //return to client  
//        echo "1"; //return to client  
       }  
    else  
    {  
            fwrite($open,"Wrong Username or password!");  
            echo "Login Failed"; //return to client  
        }  
}  
else  
{  
    fwrite($open,"No password");  
    echo "No Username or Password"; //return to client  
}  
fclose($open);  
?>  
</body>  
</html>


运行效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值