Serializing and deserializing AMF0 Mediaserver2 calls with AS3
I’m currently working on a multiplayer game (well, 2 player), a flex app which uses Flash Media Server2.
I use the Command Pattern in the app for “player moves”. I have a IGameCommand interface and a bunch of Command classes which implement it. Users select/create moves (command instances) which they send to the Media Server using AMF0 . The Media Server then validates both moves, and sends them back to the players, at which point the client side flashes execute the commands.
Here the tricky bit was the serializing / deserializing, as AMF0 only handles generic Objects… I didn’t want to have this massive switch statement to determine the type of command, then serialize it… Miraculously I recalled this blog post by Colin Moock, and salvation was at hand! I love AS3.
It turns out that in flash.utils there are a few VERY useful functions…
first, flash.utils.getQualifiedClassName() returns a string like : “net.sakri.commands::KickAss” (I’m not sure why the double colon, I’ve seen that syntax before in php and so). As an argument, you can pass an instance of an object, or the classname. This is perfect for the serializing, as the serialized object can be given a variable which holds the “qualified” name of the class that it was serialized from.
Below is an example implementation inside a Command classs (function getSerializedAMF0Object():Object is defined in IGameCommand interface):
[as]
public function getSerializedAMF0Object():Object{
var obj:Object=new Object();
obj.qualified_class_name=getQualifiedClassName(this);
//rest of props
return obj;
}
[/as]
This is kosher AMF0. The server then pushes such serialized commands to both players, and here is the code which releaved me from the nasty switch statement:
[as]
public function commandFromServer(c:Object):void{
var ClassReference:Class = getDefinitionByName(c.qualified_class_name) as Class;
var command:IGameMoveCommand=new ClassReference();
//pass the rest of class props from the serialized object,
//all of which adhere to the IGameMoveCommand interface
}
[/as]
The reason this rocks so much, is that I can now create as many commands as I like, without having to touch the send/receive, serialize/deserialize code. This method could also be used for “real” serializing, meaning, you could store your data objects as xml or strings or whatever, and know that painless instantiation awaits the stored objects return 

September 8th, 2007 at 3:22 am
Hey, please keep posting!!!
Nice work and blog! greetings arrrrrrrr
September 9th, 2007 at 7:41 pm
aw
Thanks for that Alex! I’ve just found out that I’ll be speaking at some events again soon, meaning I’ll have more material to blog about
The summer has been pretty quiet on this blog… but can you blame me? Back to School for the kids, back to blogging for me 