Using CCHttpClient in Cocos2d-X
Before using CCHttpClient, you must first build an Apache server
For how to build an Apache server and use an Apache server, refer to the following blog:
Program instance 1: Use CCHttpClient in Cocos2d-X for login verification
Use VS2012 to compile the following code (server-side code ):
# Include
# Include
# Include
Void main () {// set the HTML language printf (Content-type: text/html); // obtain the user-passed parameter char * queryString = getenv (QUERY_STRING) through the environment variable ); // break down the string queryString // split the string queryString into two strings. '|' is the separator char * username = strtok (queryString, |); char * password = strtok (NULL, |); // determine whether the user name and password are entered correctly if (0 = strcmp (username, aaa) & 0 = strcmp (password, bbb )) {printf (Login success !); } Else {printf (Login Error !); }}
Copy the program to the Apache server after compilation.
In the browser, enter: http: // localhost/cgi-bin/login. cgi? Aaa | bbb
In the browser, enter: http: // localhost/cgi-bin/login. cgi? Aaaa
The above example proves that the server-side program is successfully compiled and the program implements a simple verification. When the user passes the parameter aaa | bbb, the verification is successful, verification fails when the parameter passed by the user is not aaa | bbb
Customer Service Code
When the Cocos2d-X runs this program as a client, first create an HttpClient class and add the following code in HttpClient. h.
#ifndef __HttpClient_H__#define __HttpClient_H__#include cocos2d.h#include cocos-ext.husing namespace cocos2d::extension;USING_NS_CC;class HttpClient : public CCLayer{public:static CCScene* scene();CREATE_FUNC(HttpClient);bool init(); void httpResponse(CCHttpClient* client, CCHttpResponse* response);};#endif
Add the following code to HttpClient. cpp:
# Include HttpClient. hCCScene * HttpClient: scene () {CCScene * s = CCScene: create (); HttpClient * layer = HttpClient: create (); s-> addChild (layer ); return s;} bool HttpClient: init () {CCLayer: init (); // obtain the CCHttpClient * httpClient = CCHttpClient: getInstance (); // create a request CCHttpRequest * request = new CCHttpRequest; // set the request URL request-> setUrl (http: // localhost/cgi-bin/login. cgi? Aaa | bbb); // set the response callback function to read responserequest-> setResponseCallback (this, httpresponse_selector (HttpClient: httpResponse )); // set the request type (GET, POST, etc.) request-> setRequestType (CCHttpRequest: kHttpGet); // send the request httpClient-> send (request ); // release request-> release (); return true;} // define the HttpClient response function void HttpClient: httpResponse (CCHttpClient * client, CCHttpResponse * response) {// if server access fails if (! Response-> isSucceed () {// defines a pointer to save the error message const char * err = response-> getErrorBuffer (); // print the error message CCLog (response error = % s, err); return ;}// create a vector to save the data transmitted by the server std: vector
* VChar = response-> getResponseData (); std: string str; std: vector
: Iterator it; for (it = vChar-> begin (); it! = VChar-> end (); it ++) {str + = * it;} // print the data transmitted from the server to the customer service client CCLog (% s, str. c_str ());}
Execution result:
In HttpClient. cpp
// Set the request access address request-> setUrl (http: // localhost/cgi-bin/login. cgi? Aaa | bbb );
Change
// Set the request access address request-> setUrl (http: // localhost/cgi-bin/login. cgi? Aaa | bbb );
Result:
Program Example 2: Using CCHttpClient in the Cocos2d-X enables the client to send data to the server to process customer service data and return data
Use VS2012 to compile the following code (server-side code ):
# Include
# Include
# Include
Void main () {// set the HTML language printf (Content-type: text/html); // get the length of the uploaded data char * contentLength = getenv (CONTENT_LENGTH ); // convert the string into int length = atoi (contentLength); // print the Data length printf (content length = % d, length ); // dynamic memory allocation char * buf = (char *) malloc (length); // clears the buf to memset (buf, 0, length); // sets the stdin (buffer) read the data in the buf fread (buf, length, 1, stdin); // print the data in the buf printf (% s, buf ); // release the memory free (buf );}
Client code:
# Include HttpClient. hCCScene * HttpClient: scene () {CCScene * s = CCScene: create (); HttpClient * layer = HttpClient: create (); s-> addChild (layer ); return s;} bool HttpClient: init () {CCLayer: init (); // obtain the CCHttpClient * httpClient = CCHttpClient: getInstance (); // create a request CCHttpRequest * request = new CCHttpRequest; // set the request type to post request-> setRequestType (CCHttpRequest: kHttpPost ); // set the request access address request-> setUrl ( http://localhost/cgi-bin/login1.cgi ); // Set the callback function request-> setResponseCallback (this, httpresponse_selector (HttpClient: httpResponse )); // set the data request sent to the server-> setRequestData (aaa | bbb |, 8); // connection timeout httpClient-> setTimeoutForConnect (30 ); // send the request httpClient-> send (request); // release the request-> release (); return true ;}// define the HttpClient response function void HttpClient :: httpResponse (CCHttpClient * client, CCHttpResponse * response) {// if the server access fails if (! Response-> isSucceed () {// defines a pointer to save the error message const char * err = response-> getErrorBuffer (); // print the error message CCLog (response error = % s, err); return ;}// create a vector to save the data transmitted by the server std: vector
* VChar = response-> getResponseData (); std: string str; std: vector
: Iterator it; for (it = vChar-> begin (); it! = VChar-> end (); it ++) {str + = * it;} // print the data transmitted from the server to the customer service client CCLog (% s, str. c_str ());}
Execution result:
Program Example 3: Using CCHttpClient in Cocos2d-X to implement a simple login function
Server code:
Use VS2012 to compile the following code
# Include
# Include
# Include
Void main () {// set the HTML language printf (Content-type: text/html); // get the length of the uploaded data char * contentLength = getenv (CONTENT_LENGTH ); // convert the string into int length = atoi (contentLength); // dynamic memory allocation char * buf = (char *) malloc (length ); // reset the buf to memset (buf, 0, length); // read the data in the stdin (buffer zone) to fread (buf, length, 1, stdin) in the buf ); // break down the string queryString // split the string queryString into two strings. '|' is the separator char * username = strtok (buf, |); char * password = strtok (NULL, |); // determines whether the user name and password are entered correctly // if (0 = strcmp (username, aaa) & amp; 0 = strcmp (password, bbb) {printf (0) ;}// incorrect password for username input else if (0! = Strcmp (username, aaa) & 0 = strcmp (password, bbb) {printf (1 );} // correct password for username input error else if (0 = strcmp (username, aaa) & 0! = Strcmp (password, bbb) {printf (2) ;}// the username and password are both incorrectly entered. else {printf (3 );} // release the memory free (buf );}
Functions implemented on the server:
1. Set the correct username to aaa and the correct password to bbb.
2. Obtain the user name and password sent from the client to the server.
3. Determine whether the user name and password are correct
4. When both the user name and password are correct, send 0 to the client
5. When the user name is incorrect and the password is correct, send 1 to the client
6. When the user name is correct and the password is incorrect, send 2 to the client
7. Send 3 to the client when the user name or password is incorrect
Copy the exe file compiled from the above Code to C: Program FilesApache Software FoundationApache2.2cgi-bin, and name the exe login. cgi
Use a Cocos2d-X to achieve the login function of the client:
First create a plist file in xml format for processing Chinese, because the use of Chinese directly in the Cocos2d-X will appear garbled, create an xml file in information. plist format
Username
User Name
Password
Password
Isusername
Incorrect user name
Ispassword
Incorrect password
Login
Logon successful
Create a Login class and add the following code in Login. h.
# Ifndef _ Login_H _ # define _ Login_H _ # include cocos2d. h # include cocos-ext.husing namespace cocos2d: extension; USING_NS_CC; class Login: public CCLayer {public: static CCScene * scene (); bool init (); CREATE_FUNC (Login ); // menu response function void menuHandler (CCObject *); // defines the HttpClient response function void httpResponse (response * client, response * response); CCLabelTTF * label3; CCLabelTTF * label4; CCLabelTTF * label5; char strName [256]; char strPassword [256]; CCEditBox * m_pEditName; CCEditBox * m_pEditPassword;}; # endif
Add the following code to Login. cpp:
# Include Login. hCCScene * Login: scene () {static CCScene * scene = CCScene: create (); Login * layer = Login: create (); scene-> addChild (layer ); return scene;} bool Login: init () {CCLayer: init (); // obtain the window size. CCSize winSize = CCDirector: shareddire()-> getWinSize (); char UserName [256]; // Save the UserName char Password [256]; // Save the Password char isUserName [256]; // Save the UserName judgment result char isPassword [256]; // Save the judgment result of the password char Login [256]; // Save the logon result // create a dictionary class for reading the xml file CCDictionary * dict = CCDictionary in plist format :: createWithContentsOfFile (information. plist); // from infmation. in plist, read the username const CCString * username = dict-> valueForKey (UserName); sprintf (username, % s, username-> getCString (); // from information. in plist, read the password const CCString * password = dict-> valueForKey (Password); sprintf (password, % s, password-> getCString (); // from information. const CCString * isusername = dict-> valueForKey (isusername); sprintf (isUserName, % s, isusername-> getCString (); // obtain information from information. const CCString * ispassword = dict-> valueForKey (ispassword); sprintf (isPassword, % s, ispassword-> getCString (); // from information. plist reads the logon result const CCString * login = dict-> valueForKey (login); sprintf (Login, % s, login-> getCString (); CCLabelTTF * label1 = CCLabelTTF:: create (UserName, Arial, 25); CCLabelTTF * label2 = CCLabelTTF: create (Password, Arial, 25); label3 = CCLabelTTF: create (isUserName, Arial, 25 ); label4 = CCLabelTTF: create (isPassword, Arial, 25); label5 = CCLabelTTF: create (Login, Arial, 25); addChild (label1); addChild (label2 ); addChild (label3); addChild (label4); addChild (label5); label1-> setPosition (ccp (winSize. width/2-100, winSize. height/2 + 100); label2-> setPosition (ccp (winSize. width/2-100, winSize. height/2 + 60); label3-> setPosition (ccp (winSize. width/2, winSize. height/2-50); label4-> setPosition (ccp (winSize. width/2, winSize. height/2-80); label5-> setPosition (ccp (winSize. width/2, winSize. height/2-50); label3-> setVisible (false); label4-> setVisible (false); label5-> setVisible (false ); // create the CCEditBox control to enter the username m_pEditName = CCEditBox: create (CCSizeMake (winSize. width/3, 30), CCScale9Sprite: create(green_edit.png); // set the position of the CCEditBox control m_pEditName-> setPosition (ccp (winSize. width-220, winSize. height/2 + 100); // Add the CCEditBox control addChild (m_pEditName); // set the size of the text in the CCEditBox m_pEditName-> setFontSize (10 ); // set the text color m_pEditName-> setFontColor (ccBLACK) in the CCEditBox; // set the CCEditBox control color m_pEditName-> setPlaceholderFontColor (ccBLACK) when the CCEditBox is null ); // set the maximum number of characters that can be entered m_pEditName-> setMaxLength (8); // set the carriage return button in the soft keyboard to m_pEditName-> setReturnType (kKeyboardReturnTypeGo ); // set the input mode // kEditBoxInputModeAny indicates that any data can be input m_pEditName-> setInputMode (kEditBoxInputModeAny); // create the CCEditBox control m_pEditPassword = CCEditBox: create (CCSizeMake (winSize. width/3, 30), CCScale9Sprite: create(yellow_edit.png); // set the position of the CCEditBox control m_pEditPassword-> setPosition (ccp (winSize. width-220, winSize. height/2 + 60); // Add the CCEditBox control addChild (m_pEditPassword); // set the color of the text in the CCEditBox m_pEditPassword-> setFontColor (ccBLACK ); // set the maximum number of characters displayed in the CCEditBox control m_pEditPassword-> setMaxLength (10); // set the INPUT attribute // kEditBoxInputFlagPassword: enter the password m_pEditPassword-> setInputFlag (kEditBoxInputFlagPassword); // set the edit type in the input edit box // kEditBoxInputModeSingleLine: Enable the Input Keyboard for any text, does not include line feed m_pEditPassword-> setInputMode (kEditBoxInputModeSingleLine); // create menu CCMenu * menu = CCMenu: create (); addChild (menu ); // create a menu item CCMenuItemImage * LoginMenu = CCMenuItemImage: create(button.png, button.png); menu-> addChild (LoginMenu); // set the menu response function LoginMenu-> setTarget (this, menu_selector (Login: menuHandler); return true;} // menu response function void Login: menuHandler (CCObject *) {sprintf (strName, % s, m_pEditName-> getText (); sprintf (strPassword, % s, m_pEditPassword-> getText (); // Save the data sent to the server char strSend [256]; sprintf (strSend, % s | % s, strName, strPassword); // obtain the CCHttpClient * httpClient = CCHttpClient: getInstance (); // create a request CCHttpRequest * request = new CCHttpRequest; // set the request type to post request-> setRequestType (CCHttpRequest: kHttpPost ); // set the request access address request-> setUrl ( http://localhost/cgi-bin/login.cgi ); // Set the callback function request-> setResponseCallback (this, httpresponse_selector (Login: httpResponse); // set the data request sent to the server-> setRequestData (strSend, sizeof (strSend); // connection timeout httpClient-> setTimeoutForConnect (30); // send the request httpClient-> send (request ); // release request-> release ();} // define the response function void Login: httpResponse (CCHttpClient * client, CCHttpResponse * response) of HttpClient) {// if server access fails if (! Response-> isSucceed () {// defines a pointer to save the error message const char * err = response-> getErrorBuffer (); // print the error message CCLog (response error = % s, err); return ;}// create a vector to save the data transmitted by the server std: vector
* VChar = response-> getResponseData (); std: string str; std: vector
: Iterator it; for (it = vChar-> begin (); it! = VChar-> end (); it ++) {str + = * it;} // print the data transmitted from the server to the customer service client CCLog (% s, str. c_str (); // convert the data uploaded from the server to the customer service to an integer int num = atoi (str. c_str (); switch (num) {case 0: // label5-> setVisible (true); break; case 1: // user name error label3-> setVisible (true); break; case 2: // Password error label4-> setVisible (true); break; case 3: // The user name and password are both incorrect. label3-> setVisible (true); label4-> setVisible (true); break; default: break ;}}
Features implemented by Customer Service:
1. Enter the user name and password
2. Send the user name and password to the server
3. receive data sent from the server to the Customer Service
4. When the received data is 0, it indicates that the user name and password are entered correctly, and "Logon successful" is displayed on the interface.
5. When the received data is 1, the user name is incorrect, the password is correct, and the "user name error" is displayed on the interface.
6. When the received data is 2, it indicates that the user name is correct, the password is incorrect, and a Password error is displayed on the interface.
4. When the received data is 3, it indicates that both the user name and password are incorrect, and "incorrect user name" and "Incorrect password" are displayed on the interface.
Execution result:
Enter aaa in the user name, bbb in the password, and click log on. The logon is successful.
Enter a in the user name and bbb in the password, and click log on. a user name error is displayed.
Enter aaa in the user name and B in the password, and then click log on. A wrong password is displayed.
Enter a in the user name and B in the password, and click log on. the user name and password are incorrect.
??
??