Cocos2dx Obtaining Network Time (2): Analysis of CCHttpClient
Create a new c ++ class named NetTime, inherit from CCNode and override the init () method. Then introduce the header files required by CCHttpClient and rapidjson. Our requirement is to return the year, month, day, hour, minute, and second of NetTime, and define their private fields and public methods respectively: 1 # ifndef _ NETTIME_H _ 2 # define _ NETTIME_H _ 3 # include "cocos2d. h "4 # include" cocos-ext.h "5 # include" CocoStudio \ Json \ rapidjson. h "6 using namespace cocos2d; 7 using namespace extension; 8 using namespace rapidjson; 9 10 class NetTime: public CCNode11 {12 public: 13 CREATE_FUNC (NetTime); 14 int getYear () {15 return _ year; 16}; 17 Int getMonth () {18 return _ month; 19}; 20 int getDay () {21 return _ day; 22}; 23 int getHour () {24 return _ hour; 25}; 26 int getMinute () {27 return _ minute; 28}; 29 int getSecond () {30 return _ second; 31}; 32 void getNetTime (); 33 void requestNetTime (); 34 private: 35 virtual bool init (); 36 int _ year, _ month, _ day, _ hour, _ minute, _ second; 37 void onHttpComplete (CCHttpClient * sender, CCHttpResponse * response ); 38 void readJson (std: string jsonStr); 39}; 40 # endif we also need a requestNetTime method to initiate an http request and implement data acquisition and parsing in the callback method, copy the preceding Code directly: 1 # include "NetTime. h "2 3 bool NetTime: init () 4 {5 bool bRet = false; 6 do 7 {8 CC_BREAK_IF (! CCNode: init (); 9 10 bRet = true; 11} while (0); 12 return bRet; 13} 14 15 void NetTime: requestNetTime () 16 {17 CCHttpRequest * request = new CCHttpRequest (); 18 request-> setUrl (" http://115.159.3.250:1227/WebTime.svc/ "); 19 request-> setRequestType (CCHttpRequest: kHttpGet); 20 request-> setTag (" WebTime "); 21 request-> setResponseCallback (this, httpresponse_selector (NetTime :: onHttpComplete); 22 CCHttpClient: getInstance ()-> send (request); 23} 24 25 void NetTime: onHttpComplete (CCHttpClient * sender, CCHttpResponse * response) 26 {27 CCHttpClient: getInstance ()-> release (); 28 if (! Response) 29 return; 30 if (0! = Strlen (response-> getHttpRequest ()-> getTag () 31 {32 CCLog ("% s completed", response-> getHttpRequest ()-> getTag ()); 33} 34 int statusCode = response-> getResponseCode (); 35 char statusString [64] ={}; 36 sprintf (statusString, "HTTP Status: % d, tag = % s ", statusCode, response-> getHttpRequest ()-> getTag (); 37 CCLog (" % s ", statusString); 38 if (! Response-> isSucceed () 39 {40 CCLog ("response failed"); 41 CCLog ("error buffer: % s", response-> getErrorBuffer (); 42 return; 43} 44 std: vector <char> * buffer = response-> getResponseData (); 45 std: string str; 46 for (unsigned I = 0; I <buffer-> size (); I ++) 47 {48 char a = (* buffer) [I]; 49 str. append (1, a); 50} 51 CCLog ("% s", str. c_str (); 52 readJson (str); 53} 54 void NetTime: readJson (std: string jsonStr) 56 {57 Document doc; 58 doc. Parse <0> (jsonStr. c_str (); 59 if (! Doc. isObject () 60 return; 61 if (doc. hasMember ("Year") & doc. hasMember ("Month") & doc. hasMember ("Day") & doc. hasMember ("Hour") & doc. hasMember ("Minute") & doc. hasMember ("Second") 62 {63 _ year = doc ["Year"]. getInt (); 64 _ month = doc ["Month"]. getInt (); 65 _ day = doc ["Day"]. getInt (); 66 _ hour = doc ["Hour"]. getInt (); 67 _ minute = doc ["Minute"]. getInt (); 68 _ second = doc ["Second"]. getInt (); 69} 70} Here The reader may not be able to help. Leandro is really a big fool, so a simple class package should be written separately! We are back to HelloWorldScene. the init method of cpp, comment out the code that previously initiated the network request, and then use our NetTime class: 1/* CCHttpRequest * request = new CCHttpRequest (); 2 request-> setUrl (" http://localhost:23244/NetTime.svc/Time "); 3 request-> setRequestType (CCHttpRequest: kHttpGet); 4 request-> setTag (" WebTime "); 5 request-> setResponseCallback (this, httpresponse_selector (HelloWorld :: onHttpComplete); 6 CCHttpClient: getInstance ()-> send (request); */7 8 NetTime * netTime = NetTime: create (); 9 netTime-> requestNetTime (); 10 char timeStr [50]; 11 sprintf (timeStr, "NetTime % d-% d: % d ", 12 netTime-> getYear (), netTime-> getMont H (), netTime-> getDay (), 13 netTime-> getHour (), netTime-> getMinute (), netTime-> getSecond ()); 14 CCLabelTTF * timeLabel = CCLabelTTF: create (timeStr, "Arial", 18); 15 timeLabel-> setPosition (ccp (240, 50 )); 16 this-> addChild (timeLabel); debugging: The exception message is: the variable timeStr memory is corrupted. The most likely cause of this exception is that the getYear (), getMonth ()... method of netTime does not return the correct value. Let's take a look at the code of the NetTime class above and find that the value assignment operations for _ year, _ month, _ day, _ hour, _ minute, _ second are all in the onHttpComplete () method, that is, the callback method of the CCHttpClient network request. It can be concluded that the onHttpComplete () callback method is not executed when we use the getYear (), getMonth ()... method of netTime to return the field value. Why is the callback method not executed ?? By viewing the Cocos2dx api documentation, we found that the CCHttpClient has the following description: Once the request is completed in the singleton mode for processing asynchronous http requests, a callback function provided when the request is generated, it will be sent to the main thread here and I suddenly realized that the original CCHttpClient http request is an Asynchronous Method, and the implementation of the http request will not block the execution of the cocos2dx main thread. In this case, a better solution is to trigger a callback method after assigning values to fields in the onHttpComplete method. The callback method is registered where the external class needs to read the network time. (If you are not familiar with C ++ callback functions, refer to the C/C ++ callback function.) to meet the usage habits of cocos2dx, refer to the commonly used callback Method Design in cocos2dx, for example, the callback in CCHttpRequest. By viewing the CCHttpRequest source code, we can find that the function pointer used to call the callback method and the macro used to register the callback method: typedef void (CCObject: * SEL_HttpResponse) (CCHttpClient * client, CCHttpResponse * response); # define httpresponse_selector (_ SELECTOR) (cocos2d: extension: SEL_HttpResponse) (& _ SELECTOR) setResponseCallback implements callback method registration as follows, the two parameters are the callback method caller and function pointer: inline void setResponseCallback (CCObject * pTarget, SEL_HttpResponse pSelector) {_ pTarget = pTarget; _ pSel Ector = pSelector; if (_ pTarget) {_ pTarget-> retain () ;}} then pass in the CCHttpClicent's send (CCHttpRequest * request) method to the instance of CCHttpRequest, after the asynchronous request Http is complete, call the registered callback method to return the status and data of the Http request to us. After learning about the implementation of callback in cocos2dx, return to our NetTime in NetTime. h The header file declares the function pointer and the macro definition used for registration: typedef void (CCObject: * SEL_NetTime) (WebTime * pSender); # define netTime_selector (_ SELECTOR) (SEL_NetTime) (& _ SELECTOR) declares the fields used to store the caller instance and function pointer: SEL_NetTime _ pSelector; CCObject * _ pTarget; callers and function pointers that pass in the callback method by reloading the requestNetTime method: void NetTime: requestNetTime (CCObject * pTarget, SEL_NetTime pSelector) {requestNetTime (); _ pTarget = pTarget; _ PSelector = pSelector;} call the callback method at the end of the onHttpComplete method, and use the NetTime instance as the callback method parameter: 1 void NetTime: onHttpComplete (CCHttpClient * sender, CCHttpResponse * response) 2 {3 CCHttpClient: getInstance ()-> release (); 4 if (! Response) 5 return; 6 if (0! = Strlen (response-> getHttpRequest ()-> getTag () 7 {8 CCLog ("% s completed", response-> getHttpRequest ()-> getTag ()); 9} 10 int statusCode = response-> getResponseCode (); 11 char statusString [64] ={}; 12 sprintf (statusString, "HTTP Status: % d, tag = % s ", statusCode, response-> getHttpRequest ()-> getTag (); 13 CCLog (" % s ", statusString); 14 if (! Response-> isSucceed () 15 {16 CCLog ("response failed"); 17 CCLog ("error buffer: % s", response-> getErrorBuffer (); 18 return; 19} 20 std: vector <char> * buffer = response-> getResponseData (); 21 std: string str; 22 for (unsigned I = 0; I <buffer-> size (); I ++) 23 {24 char a = (* buffer) [I]; 25 str. append (1, a); 26} 27 CCLog ("% s", str. c_str (); 28 readJson (str); 29 if (_ pTarget & _ pSelector) 30 {31 (_ pTarget-> * _ pSel Ector) (this); 32} 33} The NetTime class is encapsulated here. Modify the code used for NetTime in HelloWorldSecne: 1 NetTime * netTime = NetTime: create (); 2 netTime-> requestNetTime (this, netTime_selector (HelloWorld: onNetTimeComplete )); onNetTimeComplete code: 1 void HelloWorld: onNetTimeComplete (NetTime * pSender) 2 {3 char timeStr [50]; 4 sprintf (timeStr, "NetTime % d-% d: % d", 5 pSender-> getYear (), pSender-> getMonth (), pSender-> getDay (), 6 pSender-> getHour (), pSender-> getMinute (), pSender-> getSecond (); 7 CCLabelTTF * timeLabel = CCLabelTTF :: create (timeStr, "Arial", 18); 8 timeLabel-> setPosition (ccp (240, 50); 9 this-> addChild (timeLabel); 10}