Ultrashock Forums > Archived Forums > Sources & Experiments
your own simple webservice

You are currently viewing our website as a guest which gives you limited access to forums, files and other resources.

Click here to join now for free, and start interacting with our members, download files and much more!

Click here if you are looking for our Flash files and other professional assets.
 
Post Reply | View first unread | Rate Thread Search this Thread | Thread Tools | Display Modes

#1
Bookmark and Share!
your own simple webservice
Old 2006-06-05 Last edited by Codemonkey : 2007-12-05 at 10:46.

So I've been reading up a bit on Flash Remoting, webservices in general and stuff like that. What snapped me off was that you either need Cold Fusion to flash remote easily, or write your own XML accoring to Flash Remoting protocol. Other standard webservices are not supported by Flash unless you write your own xml receiver/transmitter for it. At least, this is what I got from all of this so far.

So, to get my own webservice running in PHP and Flash (or rather RPC server, Remote Procedure Call), I've written a very simple remoting protocol. It supports only strings, but that can really contain anything when you use serializing (if you want to transfer Objects from flash or something). I'm very happy with how it works, so I thought I'd enrich your life with it as well

source: PHP RPC example server & Flash client
should be ready to run right away

What I did was enable flash in such a way that you can call methods in flash that are executed on the server. This way you don't need to concern yourself with sending and loading php pages yourself, you just call the method and use whatever values the webservice returned. This on its own isn't such a big deal (it's been done before), but the simplicity of the passed and received XML is why I think this is much more accessible and usable by a flash developer, or anyone really that doesn't have a strong programming background. It's lightweight compared to other available solutions out there.

This is how the remote call looks like in flash:

ActionScript Code:
  1. // setup rpc client
  2. import rpcclient.*;
  3. var rpcservice:String = "http://localhost/ultrashock/rpc/server/rpcserver_example.php";
  4. var server = new ExampleServerStub(new RPC(rpcservice));
  5.  
  6. // perform the remote procedure call and handle the response
  7. server.doTest("test stringy", showTestResult, null);
  8. function showTestResult(answer:RPCAnswer, params:Array):Void {
  9.     trace("test ok: " + answer.ok);
  10.     if (answer.ok) {
  11.         trace("result: " + answer.data); // should be "test stringy"
  12.     } else {
  13.         trace("test status: " + answer.message);
  14.     }
  15. }
I typical server response looks like this:

Code:
<?xml version="1.0"?>
<answer>
  <status>OK: some explanation provided by called method</status>
  <result><![CDATA[whatever result the called method gave back, can be xml!]]></result>
  <method>the called method, for debugging purposes</method>
</answer>
This is interpreted by the RPCClient class and converted to an RPCAnswer object, which is passed to the callback the user specified when making the remote call.

Here's all the available properties of the RPCAnswer object:

ActionScript Code:
  1. // answer: formatted server response
  2. // params: the method params passed to the server
  3. // data: whatever extra data was specified when calling the function
  4. private function callBack(answer:RPCAnswer, params:Array, data:Array):Void {
  5. trace("methodcall successful: " + answer.ok);
  6. trace("methodcall status: " + answer.message);
  7. trace("methodcall returned result: " + answer.data);
  8. // this prints out the server's response like in the code above
  9. trace("methodcall raw response: " + answer.rawdata);
  10. }
A more general approach to handling the answers could be like this (these functions are also in the source files):

ActionScript Code:
  1. // setup rpc client
  2. import rpcclient.*;
  3. var rpcservice:String = "http://localhost/ultrashock/rpc/server/rpcserver_example.php";
  4. var server = new ExampleServerStub(new RPCClient(rpcservice));
  5.  
  6. // perform a call
  7. server.doTest("test stringy", handleAnswer, showTestResult);
  8. server.doRandom(15, 25, handleAnswer, showRandom);
  9. server.doInvalidFunction(handleAnswer, null);
  10.  
  11. // handle the calls to generally check for an error
  12. // you don't have to use this, but I found myself checking answer.ok
  13. // in every single answer handler, so I made this function
  14. function handleAnswer(answer:RPCAnswer, params:Array, handler:Function) {
  15.     if (answer.ok) {
  16.         handler(answer, params);
  17.     } else {
  18.         trace(answer.message + " (method '" + answer.method + "')");
  19.     }
  20. }
  21.  
  22. // displays the string returned by the server test
  23. function showTestResult(answer:RPCAnswer, params:Array):Void {
  24.     trace("test result: " + answer.data); // should be "test stringy"
  25. }
  26. // displays the random number returned by the server
  27. function showRandom(answer:RPCAnswer, params:Array):Void {
  28.     trace("random number: " + answer.data); // should be between 15-25
  29. }
  30.  
  31.  
  32. /* output:
  33. *   test result: test stringy
  34. *   random number: 16
  35. *   ERROR: unknown function (method 'doInvalidFunction')
  36. */
Here I used the extra data parameter to specify which handler should handle the answer if the answer is ok (so no error occurred).

Now ok, random numbers on the server is pretty weird. But it's only to illustrate how this works. Imagine you need to store/fetch articles that are xml files or something. You can very easily do this with this server. In fact, I've been using this behind a hobby cms project I'm working on. It's very satisfying to work with php consistently like this, instead of hacking my way through the server response. Also debugging is a consistant operation now.

you probably think I'm mad by now, so I'll stop rambling now. Let me know what you think
XML is the glue of the future.
"Alkland's in Jeamland," I said. "Do you know what happened? I fell awake."
postbit arrow 17 comments | 1950 views postbit arrow Reply: with Quote   
Super Moderator
Codemonkey is offline Super Moderator
seperator
Posts: 5,102
2001-04-05
Age: 26
Codemonkey lives in Netherlands
Codemonkey's Avatar
seperator

Ultrashock Member Comments:
flashext flashext is offline 2006-06-05 #2 Old  
hey Codemonkey it seams that your download link is broken.
Reply With Quote  
InfinityI's Avatar InfinityI InfinityI is offline InfinityI lives in United Kingdom 2006-06-05 #3 Old  
LOL, did i just see that, a moderator posting a link to his localserver. Wow. . Great article though .
Reply With Quote  
Tcoz Tcoz is offline 2006-06-05 #4 Old  
On Windows, .Net webservices are insanely easy to set up. You can download the Visual Web Developer 2005 Express Edition for free and have one up and running in as much time as it takes to File...New...Project...C# Web Service. The Flash code is similarly easy, examples are provided all over the web. In fact, the book Flash MX Professional exclusively uses .Net web services, as do many others, because they are so incredibly simple to set up and use from Flash.

The open source Flash remoting gateway, Fluorine, is also very simple to use if Remoting is your thing. I have an example of the setup and use posted on my website, www.tcoz.com, in the code bits 'n bytes section (lower left). The protocol used by .Net (and the MM commercial product) remoting is AMF, you never get involved with messing with it though.

In addition, Fluorine, and .Net Web Services, remote many Flash objects natively, and you can map user object types to the serializer. For standard use, you never worry about the protocol, the listeners, or anything.

Another more sophisticated option that offers bidirectional communication (as opposed to web service and remoting stateless send/receive), and my preference over FCS (which as far as I'm concerned doesn't really have any use anymore) is XMLSocket. If you don't have the means to write a socket server though, you can grab ElectroServer, which has an integrated Flash object that makes calls fairly easy. I'll also be making a lightweight .Net 2.0 socket server available in a couple of weeks (already running but want to ensure it's stable and clean).

Tons of options these days.
Reply With Quote  
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator Codemonkey lives in Netherlands 2006-06-05 #5 Old  
Last edited by Codemonkey : 2006-06-05 at 22:59.
Originally posted by InfinityI
LOL, did i just see that, a moderator posting a link to his localserver. Wow. . Great article though .
ha, I forgot to replace local host with my server's address. I had to test it you know

@Tcoz
All options you mentioned require the user to run on windows, buy IIS/.NET, or write their own server. Like I said, I'm trying to not intimidate smalltime users that don't have a strong programming background, but still like a way of consistently communicating with their server, including debugging errors.
Reply With Quote  
Tcoz Tcoz is offline 2006-06-07 #6 Old  
ElectroServer runs on many platforms (it's java) and is free for 20 users, .Net is free, VS Express is free, IIS comes with XP Home/Pro/2000. VS Studio also comes with an integrated dev server that does not require IIS...AND you get SQL Server Express Edition for nothing as well. VSExpress is community based and targeted at the neophtye, but is suitable for advanced users as well. No cost here at all. It is so popular people are writing books on using this tool, and VS.Net Commercial sales are falling (which is fine, they lost money on it anyway, only the heavy duty Windows dev really needs it anyway). The tools are actually pretty unbelievable (though I still prefer mySQL, and am a total Flash Eclipse nut).

Communication debugging is generally done through the NetConn debugger (free, it's already in your Flash 8 first run WindowsSWF directory), and your dev tool attached to your server side process (for debugging the web service or remoting dlls, or socket server runtime) The great thing is, you get real runtime debugging, not just exception traces in the browser a la scripting flavor du jour.

Regarding windows, yes, but if you own Windows already you more than likely have everything you need to set up a web service in 10 minutes (including the time it will take to download VS.Net C# or VB Express). On any other platform, Eclipse has a great web service project.

Not trying to knock your suggestion Codem, but you did say that "What snapped me off was that you either need Cold Fusion to flash remote easily, or write your own XML accoring to Flash Remoting protocol. Other standard webservices are not supported by Flash unless you write your own xml receiver/transmitter for it.", and that's really not so; I've had the good fortune to get paid to explore many options, nice to be able to spread it around some.
Reply With Quote  
bambi bambi is offline 2006-06-07 #7 Old  
...you either need Cold Fusion to flash remote easily, or write your own XML accoring to Flash Remoting protocol.
i don't know if it's what you mean (probably not) but remoting isn't XML. it's a binary messaging protocol called AMF.

anyway, i don't think anyone mentioned http://www.amfphp.org the PHP solution for remoting, which is insanely easy to use.
Reply With Quote  
Tcoz Tcoz is offline 2006-06-07 #8 Old  
There is also openAMF for java remoting. Not so insanely easy to set up, but after that, works like anything else.
Reply With Quote  
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator Codemonkey lives in Netherlands 2006-06-07 #9 Old  
Ok, so it's free. I still don't like being cornered to using Microsoft stiff though, or using tools other than flash and a notepad with highlighting to write php if I don't have to. I don't think a lot of people who are just doing something very simple in php and flash are feeling comfortable with using yet another editor like VS. I've used it, you've used it, but we have a programming background, most flashers probably don't.

I've done a number of projects with people who are just doing their thing, barely manage to get their php running for their flash movie. Or some designer that wants a menu system built from xml, or store/fetch articles from a server. I know I wished I had thought of writing what I've written now, in just about an hour or so. It would save me time and headaches figuring out which sql query failed this time... and I'm sure there are lots of people who could really use this.
Reply With Quote  
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator Codemonkey lives in Netherlands 2006-06-07 #10 Old  
Originally posted by bambi
i don't know if it's what you mean (probably not) but remoting isn't XML. it's a binary messaging protocol called AMF.

anyway, i don't think anyone mentioned http://www.amfphp.org the PHP solution for remoting, which is insanely easy to use.
Yeah I know, I was confusing things I guess. I know I got fed up with the lack of cohesive information when I wrote this little thing.
Reply With Quote  
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator Codemonkey lives in Netherlands 2006-06-07 #11 Old  
actually, isn't AMF encoded in XML? I'm not sure what to make of http://amf.openlib.org/doc/ebisu.html otherwise
Reply With Quote  
bambi bambi is offline 2006-06-07 #12 Old  
nope, that's not it. i could swear i'd seen the AMF0 spec somewhere in the form of a pdf but i can't find it now. someone has reverse-engineerd AMF3 here: http://osflash.org/amf3/index

the nice thing about AMF is that it kind of works like XML, but the envelopes are tiny, parse much faster.
you can receive built-in and custom classes classes in flash through remoting (you can in XML too, but with a LOT more processing overhead).
Reply With Quote  
Tcoz Tcoz is offline 2006-06-07 #13 Old  
Correct, AMF is not XML compliant, unlike SOAP. It is optimized for transmission and does not have the overhead of extensive schema incorporation and such. Not unusual at all for any binary technology, where data transmission is expected to be far more frequent, as opposed to web services, where you are expected to intelligently package up, and return, as much data as possible when a call is made.

Great stuff.
Reply With Quote  
Mike's Avatar Mike Mike is offline Moderator Mike lives in United Kingdom 2006-06-07 #14 Old  
Well even with binary remoting, the use of remote facades would still be good practice as calls still cost (all be it not as much).

An XML endpoint does have the advantage of being manipulated by any interface you wish to plug onto it, now or down the road. Whereas Using a proprietary protocol like AMF could just lead to another area of maintenance.

Actually I do wonder in most apps if the processing of xml makes a huge difference to the end user experience? Is there a noticeable slowdown which would make a user walk? Surly if the data is fed sensibly to the interface (good pagination etc.) this would not be an issue.

I'm thinking a flash interface plugged into a RESTful architecture could be a great option & remain easy to update years down the road.

Anyway nice post CM

Hey Nutrox did you post something along these lines a few months back?
Reply With Quote  
bambi bambi is offline 2006-06-07 #15 Old  
i usually use XML for the reason mike describes.

if you build you application in such a way that you can load data in small pieces when it's required, you avoid hangups when processing large XML documents.

anyway, i think i derailed
Reply With Quote  
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator Codemonkey lives in Netherlands 2006-06-07 #16 Old  
ugh, you guys are way boyond me. I should've done my research before posting this. I think I missed the mark with this thread
Reply With Quote  
Tcoz Tcoz is offline 2006-06-07 #17 Old  
If you need near realtime data processing of say, thousands of nested objects for a complex UI, you will see a HUGE difference if you use XML (as in, a huge perf hit). Believe me I know this the hard way. The leaner and meaner, the better; remoting means you are looking for speed.

That is a proven inverse proportion; > flexibility = < speed. Not very visible for your typical remote data needs, but try doing an online game with frequent positional updates or real time network monitor with XML...nuh uh, especially not in Flash, which is notorious for slow XML perf (better now, and moreso in Flex). Just gimme an ASObject (preferably something typed, but again, mapping = perf hit. ASObjects are native and reasonably fast).

XML, when you build out serialized object trees with references to parents, can get prohibitively large. Keep in mind, I see a lot of people use remoting just because they think it is an "elite" technology and so on, when in fact they could actually use loadVars from a PHP script with the same results.

Remoting is for heavy duty work, enthusiasts, or people with very specific protocol needs. 95 percent of the flash projects I see that use remote data don't do more than an init grab or a periodic poll/update. Almost any technology can manage that.
Reply With Quote  
bambi bambi is offline 2006-06-07 #18 Old  
i don't think you missed the mark, necessarily. one of the problems with things like SOAP is they're very verbose in order to handle a broad range of conditions. your requirements in flash are smaller, so you can write an RPC-like package that uses looser, smaller XML documents.
Reply With Quote  
Thread Tools
Display Modes Rate This Thread
Rate This Thread: