{"id":494,"date":"2011-11-11T19:18:29","date_gmt":"2011-11-11T19:18:29","guid":{"rendered":"http:\/\/www.drmop.com\/?p=494"},"modified":"2011-11-12T09:49:00","modified_gmt":"2011-11-12T09:49:00","slug":"marmalade-sdk-tutorial-sending-and-retrieving-data-from-the-web","status":"publish","type":"post","link":"http:\/\/www.drmop.com\/index.php\/2011\/11\/11\/marmalade-sdk-tutorial-sending-and-retrieving-data-from-the-web\/","title":{"rendered":"Marmalade SDK Tutorial &#8211; Sending and Retrieving Data From the Web"},"content":{"rendered":"<p>This tutorial is part of the Marmalade SDK tutorials collection. To see the tutorials index\u00a0<a title=\"Marmalade SDK tutorials index\" href=\"http:\/\/www.drmop.com\/?page_id=91\">click here<\/a><\/p>\n<p>In our previous tutorial we tidied up the IwGame engine and properly separated our engine calls away from our game code. We ended up with a nice system that allows us to begin building a game. This week we are going on a slight diversion because I have recently been working on sending and retrieving data from the web. I think that its important for any game engine to be able to pull in data from outside itself as it allows us to create games that are easily upgradable without having to put a new version of the game through the app store approval process. Its also cool to be able to send data to the web as it allows us to do cool stuff such as communicating with web services, accessing functionality that could add a lot of value to our games or apps. If you just want the code to this tutorial then you can\u00a0<a title=\"IwGame_v0.200 - Marmalade SDK Game Engine\" href=\"http:\/\/www.drmop.com\/wp-content\/uploads\/2011\/11\/IwGame_v0.210.zip\" target=\"_self\">download it from here<\/a>.<\/p>\n<p>I am actually going to do a couple of tutorials today that cover this subject, the first is covering the basics of interfacing with Marmalade\u2019s IwHttp module that allows us to send GET and POST requests to a web server.<\/p>\n<p>Oh, the reason for this diversion is because over the last few days I have been working to produce a cross platform ad API that allows Marmalade SDK developers to use Inner-active\u2019s ads on any platform by writing a system that interfaces with <a title=\"Inner Active Ad Provider\" rel=\"nofollow\" href=\"http:\/\/inner-active.com\/\" target=\"_blank\">Inner-active\u2019s<\/a> ad server and pulling back text and image based ads. Thus far I have the system returning and displaying ads. I just need to write the display system into its own view control and get the click system working. once that\u2019s finished, it will become part of the IwGame game engine. I will blog about that when its finished. If you are interested in beta testing it then <a title=\"Contact Pocketeers Limited\" href=\"http:\/\/www.pocketeers.co.uk\/?page_id=8\" target=\"_blank\">please get in touch<\/a>.<\/p>\n<h2>IwHttp \u2013 Marmalade\u2019s API for Performing HTTP Requests<\/h2>\n<p>IwHttp is the base module used by the Marmalade SDK that allows you to send and receive data from a web server over http and https. IwHttp allows you to perform both GET and POST operations. We have gone one step further however and simplified and extended its usefulness creating a new class called CIwGameHttpManager. If you would like to see how to use the IwHttp class in the manager then take a look at IwGameHttp.cpp and iwGameHttp.h.<\/p>\n<h2>CIwGameHttpManager \u2013 A Queued Http Request Manager<\/h2>\n<p>CIwGameHttpManager is a singleton class that allows you to throw GET and POST requests to it. The manager will queue the requests and them one by one until no requests are left in the queue. Note that the next request is only sent after the first returns. I\u2019m not going to go into the internals of CIwGameHttpManager because the it and its associated classes constitute a lot of code. I will however explain how to use them.<\/p>\n<p>Firstly you need to instantiate and initialise the CIwGameHttpManager singleton using:<\/p>\n<pre>\r\n<blockquote>\r\n<span style=\"color: #008000;\">\/\/ Initialise the http manager<\/span>\r\nCIwGameHttpManager::Create();\r\nIW_GAME_HTTP_MANAGER-&gt;Init();<\/blockquote>\r\n<\/pre>\n<p>And before you exit your game \/ app clean-up the manager using:<\/p>\n<pre>\r\n<blockquote>\r\n<span style=\"color: #008000;\">\/\/ Clean up http manager<\/span>\r\nIW_GAME_HTTP_MANAGER-&gt;Release();\r\nCIwGameHttpManager::Destroy();<\/blockquote>\r\n<\/pre>\n<p>In your main loop, you will also need to call the manager update so that it can do its stuff using:<\/p>\n<pre>\r\n<blockquote>\r\n<span style=\"color: #008000;\">\/\/ Update http manager<\/span>\r\nIW_GAME_HTTP_MANAGER-&gt;Update();<\/blockquote>\r\n<\/pre>\n<h2>Making a GET Request \u2013 Getting Data From a Server<\/h2>\n<p>To make a GET request we need to create a persistent instance of CIwGameHttpRequest and set it up, like this:<\/p>\n<pre>\r\n<blockquote>\r\nCIwGameHttpRequest* Request = new CIwGameHttpRequest();\r\nRequest-&gt;setGET();\r\nRequest-&gt;setURI(\u201chttp:\/\/www.battleballz.com\/default.aspx\u201d);\r\nRequest-&gt;setContentAvailableCallback(&amp;DataRetrievedCallback, (void*)this);\r\nIW_GAME_HTTP_MANAGER-&gt;AddRequest(Request);<\/blockquote>\r\n<\/pre>\n<p>Note that we have set a callback function that will be called when our data is available to use. Here is an example callback:<\/p>\n<pre>\r\n<blockquote>\r\nint32 DataRetrievedCallback(void* caller, void* data)\r\n{\r\n    CIwGameHttpRequest* request = (CIwGameHttpRequest*)caller;\r\n\r\n    if (request-&gt;getProcessed())                                    <span style=\"color: #008000;\">\/\/ Check to see if our request was processed by the http manager<\/span>\r\n    {\r\n        <span style=\"color: #008000;\">\/\/ To get to our data we call request-&gt;getContent();<\/span>\r\n        <span style=\"color: #008000;\">\/\/ To get to our data length we call request-&gt;getContentLength();<\/span>\r\n        IW_GAME_HTTP_MANAGER-&gt;RemoveRequest(request);                <span style=\"color: #008000;\">\/\/ Remove request from http manager queue<\/span>\r\n    }\r\n\r\n    return 0;\r\n}<\/blockquote>\r\n<\/pre>\n<p>As you can see its ultra simple to retrieve data from the web.<\/p>\n<h2>Making a POST Request \u2013 Sending Data to a Server<\/h2>\n<p>To make a POST request we need to create a persistent instance of CIwGameHttpRequest and set it up, like this:<\/p>\n<pre>\r\n<blockquote>\r\nCIwGameHttpRequest* Request = new CIwGameHttpRequest();;\r\nRequest-&gt;setPOST();\r\nRequest-&gt;setURI(\u201chttp:\/\/test.battleballz.com\/Test.asmx \u201d);\r\nRequest-&gt;setContentAvailableCallback(&amp;DataRetrievedCallback, (void*)this);<\/blockquote>\r\n<\/pre>\n<p>Note that up to this point the setup is very similar except we specify setPOST() instead of setGET().<\/p>\n<p>However we want to send some data to the server we have to, so we have to put it somewhere, this is done using the posts body llke this:<\/p>\n<pre>\r\n<blockquote>\r\nchar length[32];\r\nconst char* body = \"&lt;?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?&gt;&lt;soap12:Envelope  xmlns:xsi=\\\"<a href=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\/%22\">http:\/\/www.w3.org\/2001\/XMLSchema-instance\\\"<\/a> xmlns:xsd=\\\"<a href=\"http:\/\/www.w3.org\/2001\/XMLSchema\/%22\">http:\/\/www.w3.org\/2001\/XMLSchema\\\"<\/a> xmlns:soap12=\\\"<a href=\"http:\/\/www.w3.org\/2003\/05\/soap-envelope\/%22\">http:\/\/www.w3.org\/2003\/05\/soap-envelope\\\"<\/a>&gt;&lt;soap12:Body&gt;&lt;HelloWorld  xmlns=\\\"<a href=\"http:\/\/www.battleballz.com\/test\/%22\">http:\/\/www.battleballz.com\/test\\\"<\/a> \/&gt;&lt;\/soap12:Body&gt;&lt;\/soap12:Envelope&gt;\";\r\nRequest-&gt;AddHeader(\"Content-Type\", \"application\/soap+xml; charset=utf-8\");\r\nsprintf(length, \"%d\", strlen(body));\r\nRequest-&gt;AddHeader(\"Content-Length\", length);\r\nRequest-&gt;setBody(body);<\/blockquote>\r\n<\/pre>\n<p>Then we add the request to the http manager<\/p>\n<pre>\r\n<blockquote>\r\nIW_GAME_HTTP_MANAGER-&gt;AddRequest(Request);<\/blockquote>\r\n<\/pre>\n<p>In the above example the body string holds an XML based SOAP request that we are sending to my test ASP.NET web service. In this case when the server gets this SOAP request it will call a method called HelloWorld which returns some data to us.<\/p>\n<p>Note that when we send data to a web server we need to send some details about that data such as its type and length. In the above example we accomplish this by adding headers to our POST request.<\/p>\n<p>When the POST has been made the web server will return a response which can be picked up in our callback function.<\/p>\n<p>Ok, that all looks quite straight forward, but we can make things much simpler if we just want to download files from our web server, in steps the IwGameFile class<\/p>\n<h2>CIwGameFile \u2013 File Class That Handles Loading of Local and External files<\/h2>\n<p>Yes, we decided to put together a quick file class that handles loading of files from local storage and from an external web server. All you have to do is pass the URL and an optional callback (my kindness knows no bounds!)<\/p>\n<p>Again, I don\u2019t want to go into the intricate details about the implementation, instead  I am opting for the telling you how to use it approach. IwGame is starting to become a small beast and I would rather spend the time improving it.<\/p>\n<p>CIwGameFile is a basic general purpose file system class that allows you to open, create, read and write files. In addition it allows you to open a file located somewhere on the web using the http protocol.<\/p>\n<p>Heres an example on how to open a local file, read some data and close the file:<\/p>\n<pre>\r\n<blockquote>\r\nCIwGameFile* file = new CIwGameFile();\r\nfile-&gt;Open(\"monkey_magic.txt\u201d);\r\nfile-&gt;Read(my_buffer, 1024);\r\nfile-&gt;Close();<\/blockquote>\r\n<\/pre>\n<p>And here\u2019s an example showing how to open a read the same file located on the web:<\/p>\n<pre>\r\n<blockquote>\r\nCIwGameFile* file = new CIwGameFile();\r\nfile-&gt;Open(\"http:\/\/www.battleballz.com\/monkey_magic.txt\u201d, false, true);\r\nfile-&gt;Read(my_buffer, 1024);\r\nfile-&gt;Close();<\/blockquote>\r\n<\/pre>\n<p>Note that the above method blocks the main loop and does essentially stops all processing of the game until the file is returned. I would instead recommend using a none blocking method like this:<\/p>\n<pre>\r\n<blockquote>\r\nCIwGameFile* file = new CIwGameFile();\r\nfile-&gt;Open(\"http:\/\/www.battleballz.com\/monkey_magic.txt\u201d);\r\nfile-&gt;setFileAvailableCallback(FileLoadedCallback);<\/blockquote>\r\n<\/pre>\n<p>And our callback would look something like this:<\/p>\n<pre>\r\n<blockquote>\r\nint32 FileLoadedCallback(void* caller, void* data)\r\n{\r\n\tCIwGameFile* file = (CIwGameFile*)caller;\r\n\tfile-&gt;Read(my_buffer, 1024);\r\n\tfile-&gt;Close();\r\n\r\n\treturn 0;\r\n}<\/blockquote>\r\n<\/pre>\n<p>IwGameFile still requires a few upgrades to complete its functionality. Here are a few planned updates:<\/p>\n<ul>\n<li>None blocking local file I\/O<\/li>\n<li>Timeout check needs adding to blocking http downloads<\/li>\n<li>Add methods for reading \/ writing common types<\/li>\n<\/ul>\n<h2>Other additions to IwGame<\/h2>\n<p>You will notice that a few other bits and bobs have appeared in the game engine that i have not mentioned thus far. These include:<\/p>\n<ul>\n<li>IwGameString \u2013 This is a basic string class that supports string builder type string building to cut down on memory allocations as well as stream type searching and some other utility stuff<\/li>\n<li>IwGameImage \u2013 This class has been upgraded to support JPEG as well as creation of images from memory based files. Will cover this in more detail in my next blog<\/li>\n<\/ul>\n<p>Well that\u2019s it for this blog, as usual you can <a title=\"IwGame_v0.200 - Marmalade SDK Game Engine\" href=\"http:\/\/www.drmop.com\/wp-content\/uploads\/2011\/11\/IwGame_v0.210.zip\" target=\"_self\">download the latest code from here<\/a><\/p>\n<p>See you soon, with another (smaller thankfully) article.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial is part of the Marmalade SDK tutorials collection. To see the tutorials index\u00a0click here In our previous tutorial we tidied up the IwGame engine and properly separated our engine calls away from our game code. We ended up with a nice system that allows us to begin building a game. This week we [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4,13,155,29,43,118,44,154,42,28,148,3,45,1],"tags":[197,192,195,193,194,198,718,196],"class_list":["post-494","post","type-post","status-publish","format-standard","hentry","category-airplay-sdk","category-android-app-development","category-apps","category-blackberry-playbook","category-blackberry-playbook-app-development","category-c-programming","category-game-and-app-development","category-games","category-ios-app-development","category-marmalade-sdk","category-pocketeers-limited","category-programming","category-samsung-bada-development","category-uncategorized","tag-get","tag-iwgame-game-engine","tag-iwgamefile","tag-iwgamehttpmanager","tag-iwgamestring","tag-iwhttp","tag-marmalade-sdk","tag-post"],"_links":{"self":[{"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/posts\/494","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/comments?post=494"}],"version-history":[{"count":6,"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/posts\/494\/revisions"}],"predecessor-version":[{"id":502,"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/posts\/494\/revisions\/502"}],"wp:attachment":[{"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/media?parent=494"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/categories?post=494"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.drmop.com\/index.php\/wp-json\/wp\/v2\/tags?post=494"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}