天天看點

【玩轉cocos2d-x之三十一】弱聯網與伺服器的通訊

原創作品,轉載請标明: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      

詳細可見http://www.w3school.com.cn/php

3.伺服器php處理代碼

這裡我直接修改了首頁index.html。會C++應該都能看懂,先是打開一個log.txt,接收到username和password,如果是username是jackystudio,password是123的話,把username和password寫入log.txt,并傳回登入成功,如果username或password錯誤時傳回登入失敗。如果未接收到則傳回沒有使用者名密碼。

3.1.采用get方式代碼

[php]  view plain copy

  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方式代碼

[php]  view plain copy

  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.按鈕請求處理

[cpp]  view plain copy

  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.         request->setUrl(str1.c_str());//設定請求的url,隻是請求頁面的url,并不包含username和password  
  30.         request->setRequestType(CCHttpRequest::kHttpPost);//設定為Post模式  
  31.         request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//設定響應的回調  
  32.         const char* postData = str2.c_str();  
  33.         request->setRequestData(postData, strlen(postData));//設定請求資料,也就是username和password  
  34.         request->setTag("POST test");  
  35.         CCHttpClient::getInstance()->send(request);//發送請求  
  36.         request->release();//釋放請求  
  37.     }  
  38. }  

4.2.響應回調處理

[cpp]  view plain copy

  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.     std::vector<char> *buffer = response->getResponseData();//接收響應資訊  
  11.     string recieveData;  
  12.     for (unsigned int i = 0; i < buffer->size(); i++)  
  13.     {    
  14.         recieveData += (*buffer)[i];    
  15.     }  
  16.     size_t begin= recieveData.find("<body>")+6;//這裡簡單處理,擷取<body>标簽内資料,即是響應内容  
  17.     size_t end= recieveData.find("</body>");  
  18.     string result(recieveData,begin,end-begin);  
  19.     m_labelStatusCode->setString(result.c_str());  
  20. }  

5.效果圖

5.1.Apache運作(Get和Post兩種效果都是一樣的)

(1)帳号密碼正确時

【玩轉cocos2d-x之三十一】弱聯網與伺服器的通訊

(2)帳号密碼錯誤時

【玩轉cocos2d-x之三十一】弱聯網與伺服器的通訊

5.2.關閉Apache

【玩轉cocos2d-x之三十一】弱聯網與伺服器的通訊

6.源碼下載下傳

下載下傳位址:http://download.csdn.net/detail/jackyvincefu/6713471