First, you need to build an Apache server before using Cchttpclient.
To build Apache server and use Apache server method can refer to the following blog:
Build Apache server under Windows: http://blog.csdn.net/u010105970/article/details/41276451
Developing a CGI program based on the Apache server: http://blog.csdn.net/u010105970/article/details/41278489
Step-by-step teaching you to use CGI to implement a simple backdoor: http://blog.csdn.net/u010105970/article/details/41345967
Program Example 1: Use Cchttpclient for login verification in Cocos2d-x
Compile the following code using VS2012 (server-side code):
#include <stdio.h> #include <stdlib.h> #include <string.h>void main () { //Set HTML language printf (" Content-type:text/html\n\n "); User-passed parameters char* queryString = getenv ("query_string") through environment variables; Break down the string QueryString //Divide the string querystring into two strings, ' | ' For delimiter char* username = strtok (queryString, "|"); char* password = strtok (NULL, "|"); Determine if the user name and password are entered correctly if (0 = = strcmp (username, "AAA") && 0 = = strcmp (password, "BBB")) { printf (" Login success!<br> "); } else { printf ("Login Error!<br>");} }
Copy program to Apache server after successful compilation
In the browser, type: HTTP://LOCALHOST/CGI-BIN/LOGIN.CGI?AAA|BBB
In the browser, type: HTTP://LOCALHOST/CGI-BIN/LOGIN.CGI?AAAA
The above example proves that the server-side program compiles successfully, and the program implements a simple verification that the validation succeeds when the user passes a parameter that is AAA|BBB and the validation fails when the parameter passed by the user is not aaa|bbb
The Code of the customer service side
When Cocos2d-x executes this program as a customer service, first create a httpclient class and add the following code to HttpClient.h
#ifndef __httpclient_h__#define __httpclient_h__#include "cocos2d.h" #include "cocos-ext.h" using 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 in the HttpClient.cpp
#include "HttpClient.h" ccscene* Httpclient::scene () {ccscene* s = ccscene::create (); httpclient* layer = Httpclient::create (); S->addchild (layer); return s;} BOOL Httpclient::init () {cclayer::init (); Get a network share instance cchttpclient* httpClient = Cchttpclient::getinstance (); Create a request cchttprequest* requests = new Cchttprequest; Set the address of the requested access 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 type of request (GET, post, etc.) Request->setrequesttype (cchttprequest::khttpget); Send request Httpclient->send (requests); Release request Request->release (); return true;} Defines the HttpClient response function void Httpclient::httpresponse (cchttpclient* client, cchttpresponse* response) {//If the Access server fails if (! Response->issucceed ()) {//define a pointer to hold error message const char* ERR = Response->geterrorbuffer (); Print error message Cclog ("Response error =%s", err); return;} Create a vector to save the data passed from the server std::vector<char>* Vchar = Response->getresponsedata (); std::string Str;std::vector<char>::iterator it; for (it = Vchar->begin (); It! = Vchar->end (); it++) {str + = *it;} Print server to the customer service data cclog ("%s", Str.c_str ());}
Execution Result:
HttpClient.cpp the Httpclient::init () in the
Set the address requested for Access Request->seturl (<a target=_blank href= "HTTP://LOCALHOST/CGI-BIN/LOGIN.CGI?AAA|BBB" >http:// localhost/cgi-bin/login.cgi?aaa|bbb</a>);
Change into
Set the address requested for Access Request->seturl (<a target=_blank href= "HTTP://LOCALHOST/CGI-BIN/LOGIN.CGI?AAA|BBB" >http:// localhost/cgi-bin/login.cgi?aaa|bbb</a>);
After the execution result:
Program Example 2: Use Cchttpclient in cocos2d-x to implement customer service end to the server to send Data server processing customer service side data and return data
Compile the following code using VS2012 (server-side code):
#include <stdio.h> #include <stdlib.h> #include <string.h>void main () { //Set HTML language printf (" Content-type:text/html\n\n "); The length of the data to be uploaded char* contentlength = getenv ("Content_length"); Converts a string into a shape int length = atoi (contentlength); Print the length of the data printf ("Content length =%d<br>\n", "Length"); Dynamic memory allocation char* BUF = (char*) malloc (length); The BUF is cleared 0 memset (buf, 0, length); Reads data from the stdin (buffer) into the BUF fread (buf, length, 1, stdin); Print data in buf printf ("%s<br>\n", buf); Release Memory free (BUF);}
Customer-side code:
#include "HttpClient.h" ccscene* Httpclient::scene () {ccscene* s = ccscene::create (); httpclient* layer = Httpclient::create (); S->addchild (layer); return s;} BOOL Httpclient::init () {cclayer::init (); Get a network share instance cchttpclient* httpClient = Cchttpclient::getinstance (); Create a request cchttprequest* requests = new Cchttprequest; The type of the set request is post Request->setrequesttype (cchttprequest::khttppost); Set the address of the requested access Request->seturl ("http://localhost/cgi-bin/login1.cgi"); Set the callback function Request->setresponsecallback (this, Httpresponse_selector (Httpclient::httpresponse)); Set the data sent to the server Request->setrequestdata ("aaa|bbb|", 8); Connection Timeout Httpclient->settimeoutforconnect (30); Send request Httpclient->send (requests); Release request Request->release (); return true;} Defines the HttpClient response function void Httpclient::httpresponse (cchttpclient* client, cchttpresponse* response) {//If the Access server fails if (! Response->issucceed ()) {//define a pointer to hold error message const char* ERR = Response->geterrorbuffer (); Print error message Cclog ("Response error =%s", err); return;} Create a vector to save the data passed from the server std::vector<char>* Vchar = Response->getresponsedata (); std::string Str;std::vector<char>::iterator it; for (it = Vchar->begin (); It! = Vchar->end (); it++) {str + = *it;} Print server to the customer service data cclog ("%s", Str.c_str ());}
Execution Result:
Program Example 3: Use Cchttpclient in cocos2d-x to implement a simple login function
Server-side code:
Compile the following code using VS2012
#include <stdio.h> #include <stdlib.h> #include <string.h>void main () {//Set HTML language printf ("Content-ty Pe:text/html\n\n "); The length of the data to be uploaded char* ContentLength = getenv ("Content_length"); Converts a string into a shape int length = atoi (contentlength); Dynamic memory allocation char* BUF = (char*) malloc (length); The BUF is cleared 0 memset (buf, 0, length); Reads data from the stdin (buffer) into the BUF fread (buf, length, 1, stdin); Break down the string querystring//Divide the string querystring into two strings, ' | ' For delimiter char* username = strtok (buf, "|"); char* password = strtok (NULL, "|"); Determine if the user name and password are entered correctly//username and password are entered correctly if (0 = = strcmp (username, "AAA") && 0 = = strcmp (password, "BBB")) { printf ("0"); }//Username input Incorrect password Enter correct else if (0! = strcmp (username, "AAA") && 0 = = strcmp (password, "BBB")) {PR intf ("1"); }//Username enter correct password input error else if (0 = = strcmp (username, "AAA") && 0! = strcmp (password, "BBB")) {printf (" 2 "); }//user name and password are entered incorrectly else{printf ("3"); }//Release memory free (BUF);}
Server-side Implementation features:
1, set the correct user name AAA, the correct password for BBB
2 . Get user name and password from client side to server
3. determine if the user name and password are correct
4, when the user name and password are correct, send 0 to the client
5, when the user name is wrong, the password is correct, send 1 to the client
6, when the user name is correct, password error, send 2 to the client
7, when the user name is wrong, the password is also wrong, send 3 to the client
Copy the above code into the exe file to C:\Program Files\apache software foundation\apache2.2\cgi-bin, and the EXE from the name login.cgi
Clients that use Cocos2d-x to implement the login function:
First, create an XML-formatted plist file for processing Chinese, because the use of Chinese directly in Cocos2d-x will be garbled, creating an XML file in information.plist format
<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE plist Public "-//apple computer//dtd plist 1.0//en" "Http://www.apple.com/DTDs/PropertyList-1.0.dtd" >< Plist version= "1.0" > <dict> <key>username</key> <string> user name </string > <key>password</key> <string> password </string> <key>isusername</key > <string> User name error </string> <key>ispassword</key> <string> password error </ string> <key>login</key> <string> Login Success </string> </dict></ Plist>
Create a login class and add the following code to the Login.h
#ifndef _login_h_#define _login_h_#include "cocos2d.h" #include "cocos-ext.h" using 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 response function of the httpclient void HttpResponse (cchttpclient* client, cchttpresponse* response); cclabelttf* label3; cclabelttf* Label4; cclabelttf* Label5; Char strname[256]; Char strpassword[256]; cceditbox* M_peditname; Cceditbox* M_peditpassword;}; #endif
Add the following code in the Login.cpp
#include "Login.h" ccscene* Login::scene () {static ccscene* scene = Ccscene::create (); login* layer = Login::create (); Scene->addchild (layer); return scene;} BOOL Login::init () {cclayer::init (); Get the size of the window ccsize winsize = Ccdirector::shareddirector ()->getwinsize (); Char username[256];//save user name char password[256];//save password char isusername[256];//save user name judgment result char ispassword[256];//save secret The judgment result of the code char login[256];//Save the login result//create a dictionary class to read the plist format XML file ccdictionary* dict = Ccdictionary::createwithconten Tsoffile ("Information.plist"); Read user name from Infmation.plist const ccstring* username = Dict->valueforkey ("username"); sprintf (UserName, "%s", username->getcstring ()); Read the password from information.plist const ccstring* password = dict->valueforkey ("password"); sprintf (Password, "%s", password->getcstring ()); The result of reading the user name from Information.plist const ccstring* isusername = Dict->valueforkey ("Isusername"); sprintf (Isusername, "%s", Isusername->getcstring ()); The judgment result of reading the password from information.plist const ccstring* Ispassword = Dict->valueforkey ("Ispassword"); sprintf (Ispassword, "%s", ispassword->getcstring ()); The result of reading the login from information.plist 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-WINSIZE.HEIGHT/2 + 100)); Label2->setposition (CCP (WINSIZE.WIDTH/2-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 a Cceditbox control to enter the user name M_peditname = cceditbox::create (Ccsizemake (WINSIZE.WIDTH/3, +), Ccscale9sprite::create (" Green_edit.png ")); Sets the position of the Cceditbox control M_peditname->setposition (CCP (winsize.width-220, WINSIZE.HEIGHT/2 + 100)); Add Cceditbox control AddChild (m_peditname); Set the size of the Cceditbox Chinese text m_peditname->setfontsize (10); Set the color M_peditname->setfontcolor (ccblack) of the Cceditbox Chinese text; When setting Cceditbox to null, the color of the Cceditbox control M_peditname->setplaceholderfontcolor (Ccblack); Sets the maximum number of characters that can be entered m_peditname->setmaxlength (8); Sets the appearance of the Enter button in the soft keyboard m_peditname->setreturntype (Kkeyboardreturntypego); Setting the input mode//keditboxinputmodeany means that you can enter any data m_peditname->setinputmode (KEDITBOxinputmodeany); Create the Cceditbox control M_peditpassword = Cceditbox::create (Ccsizemake (WINSIZE.WIDTH/3, +), ccscale9sprite::create ("Yellow _edit.png ")); Sets the position of the Cceditbox control M_peditpassword->setposition (CCP (winsize.width-220, WINSIZE.HEIGHT/2 + 60)); Add Cceditbox control AddChild (M_peditpassword); Set the color M_peditpassword->setfontcolor (ccblack) of the Cceditbox Chinese text; Sets the maximum number of characters displayed in the Cceditbox control M_peditpassword->setmaxlength (10); Set the Input property//keditboxinputflagpassword: Enter the password M_peditpassword->setinputflag (Keditboxinputflagpassword); Set the edit type of the input edit box//keditboxinputmodesingleline: The input keyboard to open any text, not including line break M_peditpassword->setinputmode (Keditboxinpu Tmodesingleline); Create menu ccmenu* menus = ccmenu::create (); AddChild (menu); Create a menu item ccmenuitemimage* loginmenu = Ccmenuitemimage::create ("Button.png", "button.png"); Menu->addchild (Loginmenu); Set 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 data sent to the server char strsend[256]; sprintf (Strsend, "%s|%s", StrName, strpassword); Get a network share instance cchttpclient* httpClient = Cchttpclient::getinstance (); Create a request cchttprequest* requests = new Cchttprequest; The type of the set request is post Request->setrequesttype (cchttprequest::khttppost); Set the address of the requested access Request->seturl ("http://localhost/cgi-bin/login.cgi"); Set the callback function Request->setresponsecallback (this, Httpresponse_selector (Login::httpresponse)); Sets the data sent to the server Request->setrequestdata (strsend, sizeof (strsend)); Connection Timeout Httpclient->settimeoutforconnect (30); Send request Httpclient->send (requests); Release request Request->release (); }//definition httpclient response function void Login::httpresponse (cchttpclient* client, cchttpresponse* Response) {//If the Access server fails if (!response->issucceed ()) {//define a pointer to save the error message const char* err = Response->geterrorbuffer (); Print error message Cclog ("Response error =%s", err); Return }//Create a vector to save the data passed from the server std::vector<char>* Vchar = Response->getresponsedata (); std::string str; Std::vector<char>::iterator it; for (it = Vchar->begin (); It! = Vchar->end (); it++) {str + = *it; }//print server to the customer service data cclog ("%s", Str.c_str ()); Convert the server to customer service data into int num = atoi (STR.C_STR ()); Switch (num) {case 0://login succeeded Label5->setvisible (true); Break Case 1://User name error label3->setvisible (TRUE); Break Case 2://Password Error label4->setvisible (true); Break Case 3://user name and password are both error label3->setvisible (TRUE); Label4->setvisible (TRUE); Break Default:break; }}
Functions implemented by the customer service side:
1. Enter user name and password
2. Send user name and password to server
3, the receiving server sends the data to the customer service side
4, when the data received is 0 o'clock, indicating that the user name and password entered the correct, on the interface display "Login Success"
5, when the data received is 1 o'clock, indicating that the user name is wrong, the password is correct, the interface displays "User name error"
6, when the data received is 2 o'clock, indicating that the user name is correct, the password is wrong, the interface display "Password Error"
4, when the data received is 3 o'clock, indicating that the user name and password are wrong, the interface displays "User name error", "Password error "
Execution Result:
When you enter the AAA in the user name, enter BBB in the password, and then click Login to display the login success
When you enter a in the user name, enter BBB in the password, and then click Login to display the user name error
When you enter AAA in the user name, enter B in the password, and then click Login to display the password error
When you enter a in the user name, enter B in the password, and then click Login to display the user name error, password error
Using Cchttpclient for network communication in Cocos2d-x