分享

【玩转cocos2d-x之三十一】服务器的网络通信编程

 Kitsdk 2014-02-24

原创作品,转载请标明http://blog.csdn.net/jackystudio/article/details/17347069


这里采用Apache+php搭建了一个简易服务器,服务端用php语言,客户端采用cocos2d-x的CCHttpClient类通过http方式访问服务端资源。模拟了cocos2d-x提交账户和密码到服务端,服务端校验账号密码,如果正确返回客户端成功登录,如果错误则返回错误信息,同时在服务端后台保存登录log。第一次接触php,语法上和C/C++还是蛮像的,主要是给出一个cocos2d-x网络实例,代码中并没有做一些防呆纠错措施。


1.搭建Apache+php网页服务器

Apche2.2 x86版下载地址:http://pan.baidu.com/s/1vNuLF

php5.2.17版下载地址:http://pan.baidu.com/s/17sFoN

搭建过程参见http://tech.163.com/06/0206/11/299AMBLT0009159K.html,这里就不安装MySQL了。

搭建成功后,打开http://127.0.0.1,就可以看到"It' works!"字样。同时打开Apache monitor监控Apache处于运行状态。我这里使用的80端口。


2.php收集表单的方式

Http定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE,对应着查改增删,这里介绍GET和POST。

用$_GET获取表单数据,表单数据对任何人都是可见的,比如

http://www.w3school.com.cn/welcome.php?username=jackystudio&password=123

用$_POST获取表单数据,表单数据则是不可见的,比如
http://www.w3school.com.cn/welcome.php


3.服务器php处理代码


这里我直接修改了主页index.html。会C++应该都能看懂,先是打开一个log.txt,接收到username和password,如果是username是jackystudio,password是123的话,把username和password写入log.txt,并返回登录成功,如果username或password错误时返回登录失败。如果未接收到则返回没有用户名密码。

3.1.采用get方式代码

  1. <html>  
  2. <body>  
  3. <?php  
  4. $open=fopen("log.txt","a" ); //Save password  
  5. if(isset($_GET["username"]) && isset($_GET["password"]))  
  6. {  
  7. if($_GET["username"]=="jackystudio" && $_GET["password"]=="123")  
  8. {  
  9. fwrite($open,"Username:".$_GET["username"]);  
  10. fwrite($open,"\r\n");  
  11. fwrite($open,"Password:".$_GET["password"]);  
  12. echo "Login Success"//return to client  
  13. }  
  14. else  
  15. {  
  16. fwrite($open,"Wrong Username or password!");  
  17. echo "Login Failed"//return to client  
  18. }  
  19. }  
  20. else  
  21. {  
  22. fwrite($open,"No password");  
  23. echo "No Username or Password"//return to client  
  24. }  
  25. fclose($open);  
  26. ?>  
  27. </body>  
  28. </html>  

3.2.采用post方式代码

  1. <html>  
  2. <body>  
  3. <?php  
  4. $open=fopen("log.txt","a" ); //Save password  
  5. if(isset($_POST["username"]) && isset($_POST["password"]))  
  6. {  
  7. if($_POST["username"]=="jackystudio" && $_POST["password"]=="123")  
  8. {  
  9. fwrite($open,"Username:".$_POST["username"]);  
  10. fwrite($open,"\r\n");  
  11. fwrite($open,"Password:".$_POST["password"]);  
  12. echo "Login Success"//return to client  
  13. }  
  14. else  
  15. {  
  16. fwrite($open,"Wrong Username or password!");  
  17. echo "Login Failed"//return to client  
  18. }  
  19. }  
  20. else  
  21. {  
  22. fwrite($open,"No password");  
  23. echo "No Username or Password"//return to client  
  24. }  
  25. fclose($open);  
  26. ?>  
  27. </body>  
  28. </html>  

4.cocos2d-x使用CCHttpClient类进行网络请求

CCHttpClient的使用这里也不赘述了,请移步官方文档How_to_use_CCHttpClient。这里在上文编辑框和点九图的基础上进行了修改。2个编辑框,分别是username和password。一个按钮点击发送请求。一个文本显示从服务器返回的结果。


4.1.按钮请求处理

  1. void TestLayer::btncallback( CCObject* pSender )  
  2. {  
  3.     bool requestType_is_get=true;//采用get方式或者post方式  
  4.     if (requestType_is_get)  
  5.     {  
  6.         CCHttpRequest* request = new CCHttpRequest();//创建请求对象  
  7.         string str1 = "127.0.0.1:80/index.html?";  
  8.         string str2 = p_User_EditBox->getText();//获取username编辑框内容  
  9.         string str3 = p_Psw_EditBox->getText();//获取password编辑框内容  
  10.         string struser="username=";  
  11.         string strpsw="&password=";  
  12.         str1=str1+struser+str2+strpsw+str3;  
  13.         request->setUrl(str1.c_str());//设置请求的url,username和password已经包含在url中  
  14.         request->setRequestType(CCHttpRequest::kHttpGet);//设置为Get模式  
  15.         request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//设置响应的回调  
  16.         request->setTag("GET test");  
  17.         CCHttpClient::getInstance()->send(request);//发送请求  
  18.         request->release();//释放请求  
  19.     }  
  20.     else  
  21.     {  
  22.         CCHttpRequest* request = new CCHttpRequest();//创建请求对象  
  23.         string str1 = "127.0.0.1:80/index.html";  
  24.         string str2 = p_User_EditBox->getText();  
  25.         string str3 = p_Psw_EditBox->getText();  
  26.         string struser="username=";  
  27.         string strpsw="&password=";  
  28.         str2=struser+str2+strpsw+str3;  
  29.   
  30.         request->setUrl(str1.c_str());//设置请求的url,只是请求页面的url,并不包含username和password  
  31.         request->setRequestType(CCHttpRequest::kHttpPost);//设置为Post模式  
  32.         request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//设置响应的回调  
  33.   
  34.         const char* postData = str2.c_str();  
  35.         request->setRequestData(postData, strlen(postData));//设置请求数据,也就是username和password  
  36.           
  37.         request->setTag("POST test");  
  38.         CCHttpClient::getInstance()->send(request);//发送请求  
  39.         request->release();//释放请求  
  40.     }  
  41. }  

4.2.响应回调处理

  1. void TestLayer::onHttpRequestCompleted( CCHttpClient* client, CCHttpResponse* response )  
  2. {  
  3.     if (!response->isSucceed())//如果响应失败,输出错误信息  
  4.     {    
  5.         CCString strError;  
  6.         strError.initWithFormat("Receive Error! \n%s\n",response->getErrorBuffer());  
  7.         m_labelStatusCode->setString(strError.getCString());  
  8.         return ;     
  9.     }    
  10.   
  11.     std::vector<char> *buffer = response->getResponseData();//接收响应信息  
  12.     string recieveData;  
  13.     for (unsigned int i = 0; i < buffer->size(); i++)  
  14.     {    
  15.         recieveData += (*buffer)[i];    
  16.     }  
  17.     size_t begin= recieveData.find("<body>")+6;//这里简单处理,获取<body>标签内数据,即是响应内容  
  18.     size_t end= recieveData.find("</body>");  
  19.     string result(recieveData,begin,end-begin);  
  20.     m_labelStatusCode->setString(result.c_str());  
  21. }  

5.效果图

5.1.Apache运行(Get和Post两种效果都是一样的)

(1)账号密码正确时


(2)账号密码错误时


5.2.关闭Apache



6.源码下载

下载地址:http://download.csdn.net/detail/jackyvincefu/6713471


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多