【玩轉cocos2d-x之三十一】弱聯網與伺服器的通訊
阿新 • • 發佈:2019-01-29
這裡採用Apache+php搭建了一個簡易伺服器,服務端用php語言,客戶端採用cocos2d-x的CCHttpClient類通過http方式訪問服務端資源。模擬了cocos2d-x提交賬戶和密碼到服務端,服務端校驗帳號密碼,如果正確返回客戶端成功登入,如果錯誤則返回錯誤資訊,同時在服務端後臺儲存登入log。第一次接觸php,語法上和C/C++還是蠻像的,主要是給出一個cocos2d-x網路例項,程式碼中並沒有做一些防呆糾錯措施。
1.搭建Apache+php網頁伺服器
搭建成功後,開啟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方式程式碼
- <html>
- <body>
- <?php
- $open=fopen("log.txt","a" ); //Save password
- if(isset($_GET["username"]) && isset($_GET["password"]))
- {
- if($_GET["username"]=="jackystudio" && $_GET["password"]=="123")
- {
-
fwrite($open,"Username:".$_GET["username"]);
- fwrite($open,"\r\n");
- fwrite($open,"Password:".$_GET["password"]);
- echo"Login Success"; //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>
3.2.採用post方式程式碼
- <html>
- <body>
- <?php
- $open=fopen("log.txt","a" ); //Save password
- if(isset($_POST["username"]) && isset($_POST["password"]))
- {
- if($_POST["username"]=="jackystudio" && $_POST["password"]=="123")
- {
- fwrite($open,"Username:".$_POST["username"]);
- fwrite($open,"\r\n");
- fwrite($open,"Password:".$_POST["password"]);
- echo"Login Success"; //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>
4.cocos2d-x使用CCHttpClient類進行網路請求
礎上進行了修改。2個編輯框,分別是username和password。一個按鈕點擊發送請求。一個文字顯示從伺服器返回的結果。
4.1.按鈕請求處理
- void TestLayer::btncallback( CCObject* pSender )
- {
- bool requestType_is_get=true;//採用get方式或者post方式
- if (requestType_is_get)
- {
- CCHttpRequest* request = new CCHttpRequest();//建立請求物件
- string str1 = "127.0.0.1:80/index.html?";
- string str2 = p_User_EditBox->getText();//獲取username編輯框內容
- string str3 = p_Psw_EditBox->getText();//獲取password編輯框內容
- string struser="username=";
- string strpsw="&password=";
- str1=str1+struser+str2+strpsw+str3;
- request->setUrl(str1.c_str());//設定請求的url,username和password已經包含在url中
- request->setRequestType(CCHttpRequest::kHttpGet);//設定為Get模式
- request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//設定響應的回撥
- request->setTag("GET test");
- CCHttpClient::getInstance()->send(request);//傳送請求
- request->release();//釋放請求
- }
- else
- {
- CCHttpRequest* request = new CCHttpRequest();//建立請求物件
- string str1 = "127.0.0.1:80/index.html";
- string str2 = p_User_EditBox->getText();
- string str3 = p_Psw_EditBox->getText();
- string struser="username=";
- string strpsw="&password=";
- str2=struser+str2+strpsw+str3;
- request->setUrl(str1.c_str());//設定請求的url,只是請求頁面的url,並不包含username和password
- request->setRequestType(CCHttpRequest::kHttpPost);//設定為Post模式
- request->setResponseCallback(this, httpresponse_selector(TestLayer::onHttpRequestCompleted));//設定響應的回撥
- constchar* postData = str2.c_str();
- request->setRequestData(postData, strlen(postData));//設定請求資料,也就是username和password
- request->setTag("POST test");
- CCHttpClient::getInstance()->send(request);//傳送請求
- request->release();//釋放請求
- }
- }
4.2.響應回撥處理
- void TestLayer::onHttpRequestCompleted( CCHttpClient* client, CCHttpResponse* 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();//接收響應資訊
- string recieveData;
- for (unsigned int i = 0; i < buffer->size(); i++)
- {
- recieveData += (*buffer)[i];
- }
- size_t begin= recieveData.find("<body>")+6;//這裡簡單處理,獲取<body>標籤內資料,即是響應內容
- size_t end= recieveData.find("</body>");
- string result(recieveData,begin,end-begin);
- m_labelStatusCode->setString(result.c_str());
- }
5.效果圖
5.1.Apache執行(Get和Post兩種效果都是一樣的)
(1)帳號密碼正確時
(2)帳號密碼錯誤時
5.2.關閉Apache