[Cocos2d-x] How do I automatically send a menu click callback event?
We often encounter some random bugs in our work. If the probability of a bug occurring is very low, it is very troublesome to reproduce it manually. In this case, you must consider the problematic code segment for automated execution. If the code is executed sequentially, add a loop. However, for callback events that are asynchronously executed, a loop cannot be simply added. For example, in the httpclient test example, there is an http get test menu. Click this menu once and the following callback event will be executed:
Void HttpClientTest: onMenuGetTestClicked (cocos2d: CCObject * sender)
{
// Test1
......
// Test2
{
CCHttpRequest * request = new CCHttpRequest ();
// Required fields
Request-> setUrl ("http://httpbin.org/ip ");
Request-> setRequestType (CCHttpRequest: kHttpGet );
Request-> setResponseCallback (this, httpresponse_selector (HttpClientTest: onHttpRequestCompleted ));
// Optional fields
Request-> setTag ("GET test2 ");
String empty = "empty ";
Request-> setRequestData (empty. c_str (), empty. length ());
CCHttpClient: getInstance ()-> setTimeoutForConnect (1 );
CCHttpClient: getInstance ()-> setTimeoutForRead (1 );
CCHttpClient: getInstance ()-> send (request );
// Don't forget to release it, pair to new
Request-> release ();
}
// Test3
......
// Waiting
M_labelStatusCode-> setString ("waiting ...");
}
Obviously, if you wrap this callback function with a while loop, it will lead to an endless loop of the entire test program, because this callback is executed in the main thread of cocos2dx.
So what should we do?
My solution is to first create a working thread:
// Worker thread
Static void * networkThread (void * data)
{
While (true ){
//
CCDirector: sharedDirector ()-> getschedctor ()-> scheduleSelector (
Schedule_selector (HttpClientTest: dispatchTest), HttpClientTest: getInstance (), 0, false );
Sleep (1 );
Break;
}
}
This thread sends a scheduling request to the cocos2dx scheduler every second. The scheduling event of the request is dispatchTest, and dispatchTest is the original onMenuGetTestClicked, and then starts this working thread in onMenuGetTestClicked:
Void HttpClientTest: onMenuGetTestClicked (cocos2d: CCObject * sender)
{
Pthread_create (& s_networkThread, NULL, networkThread, NULL );
Pthread_detach (s_networkThread );
}
In addition, you need to change HttpClientTest to singleton mode, and add a static getInstance () method:
HttpClientTest * s_pHttpClientTest;
// HttpClient implementation
HttpClientTest * HttpClientTest: getInstance ()
{
If (s_pHttpClientTest = NULL ){
S_pHttpClientTest = newHttpClientTest ();
}
Returns_pHttpClientTest;
}
In this way, you can click the Http get menu to automatically send the menu clicking events cyclically.