[SmartFox Pro] Simple Extension
[ July 29, 2005 ] by Marco Lapi, a.k.a Lapo
Article 2: write your first simple extension, to get in touch with all the basics of server side extensions programming with SmartFoxServer PRO


The related source file for this article is found in the "Examples/mx2004/pro_SimpleExtension" folder.

INTRODUCTION

In this tutorial we will write a very simple extension that will show you all the basics of the server side extensions programming with SmartFoxServer PRO.

The extensions will take an array of numbers and it will return the same array with the values multiplied by 2.

Before we dive into the code it's good to take a look at how the extension is loaded. First of all the Actionscript file is saved in the sfsExtensions/ folder, which is the root of all extensions in SmartFoxServer PRO.
If you take a look at the settings in the config.xml file you will find that the extensions is loaded at Zone Level in the Zone called "dbTest". This means that our extension can be called from any room within that Zone. It is also assigned a name ("simpleExt" in this case) that is going to be used in order to invoke methods on that extension.


THE CLIENT SIDE

Now it's time to open the source .FLA file and have a look at the very simple code inside it. If you quickly inspect the code in the "connect" and "chat" labels it should look familiar as it is very similar to what we have done in all the previous tutorials.

You can now position the playhead in the "chat" label and look at the code that handles the button click:

function sendValues()
{
        var obj:Object = {}
        obj.values = [100, 200, 300, 400, 500]
        
        smartfox.sendXtMessage(extensionName, "double", obj, "xml")
        
        output_txt.text += "Sent: " + obj.values + newline
}

In the first two lines an array containing five numbers is created: these are the values that we will send to the server side extension and we expect to receive an array with those five numbers multiplied by 2.

The next line is very important because it shows how we can call our custom code on the server. The sendXtMessage() is used to call our extensions and the following list shows the parameters needed:

extName   The name of the extension to call. It must be the same as declared in the config.xml.
cmd   The name of the command that should be executed by the server side extension.
params   An object containing data to pass to the server code (it can contain strings, numbers, booleans, arrays, objects).
type   It can be "xml" or "str". It represents the type of protocol being used to send the request. By default "xml" is used and your request is sent in XML format.
If you use "str" you will send the request in a raw, string-based format that can save a lot of bandwidth. You will learn more about how to use this format by following one of the next tutorials.

Back to our code, at line 10, we defined a global variable called "extensionName":

var extensionName:String = "simpleExt"

This is the name of the extension that we will call. The second argument passed to sendXtMessage() is "double", which is the name of the command that will multiply the values by 2. Then we passed the object containing the numbers array and finally we chose to use the XML format for this request.

Since XML is used by default we could have omitted the last paramater.

NOTE: SmartFoxServer uses XML format for all its messages. Even if XML can lead to larger messages when compared to pure string-based format, it allows easy debugging of the server messages and complex data serialization. Also the XML code has been optimized to reduce overhead.
The string-based format can be great for real-time action games and in all those cases where continuous and fast client updates are required. String-based (raw) format does not allow to serialize complex objects and you will be able to send simple data such as numbers, strings, etc.
More in general when sending non time-critical messages such as room updates, user updates, etc., or when dealing with turn-based games, XML is preferrable as it allows more flexibility. On the other hand when fast updates are needed you can use the raw format. Both approaches can be mixed transparently. You will learn more about this topic in the next tutorials.


THE SERVER SIDE

Now that we've sent the request from the client, it's time to see how it is handled in our server code:

function init()
{
        // Using trace will send data to the server console
        trace("Hello from the Simple Extension Example!")
}

function destroy()
{
        trace("Bye bye!")
}

function handleRequest(cmd, params, user, fromRoom)
{
        
        if (cmd == "double")
        {
                var response = {}
                
                response._cmd = "double"
                response.values = []
                
                for (var i = 0; i < params.values.length; i++)
                {
                        var n = params.values[i]
                        response.values[i] = n * 2
                }
                
                _server.sendResponse(response, -1, null, [user])
        }
}

function handleInternalEvent(evt)
{
        // Simply print the name of the event that was received
        trace("Event received: " + evt.name)
}

You can see that both the init() and destroy() method just trace a message to the console. The trace() command, like in the Flash IDE, prints your text and variables to the server console and also to the Administrator Tool trace window.
If you keep your AdminTool connected to SmartFoxServer while testing your extensions, you will receive all the trace output and you will be able to remotely debug your server code.

The important code is contained in the handleRequest() function: first we check if the command name is the one we expected, then we prepare an object called "response" with an empty array for ther server reply.

Also we add a property called "_cmd" with the name of the command. This is a convention that we will use through all the following tutorials (even if it's not mandatory to call that variable "_cmd", you will anyway need to pass a property with the command name or you will not be able to detect which command is replying on the client side).

In the next lines we cycle through the array sent from the client (params.values) and fill the response array with the doubled values.

Finally we send the result back to the client by using the _server.sendResponse()method which takes 5 parameters:

response   an object with the _cmd property specifying the name of the response command.
fromRoom   the id of the room where the response comes from (-1 if not needed).
sender   the User object of the client sending the response (null if not needed).
recipients   a list of User objects that should receive the reponse.
type   can be "xml" or "str". It represent the message format. By default "xml" is used.


BACK TO THE CLIENT

Now it's time to get back to the client side of the application and see how the server response is received.
We will use the onExtensionsResponse event handler:

smartfox.onExtensionResponse = function(resObj:Object, type:String)
{
        trace("cmd: " + resObj._cmd)
        trace("type: " + type)
        
        // We expect the response to be xml formatted
        if (type == "xml")
        {
                // Let's check if it's a "getData" message
                if (resObj._cmd == "double")
                {
                        trace("res: " + resObj.values)
                        output_txt.text += "Received: " + resObj.values + newline
                }
        }
}

The resObj object contains the data sent by the server and "type" tells us what protocol was used for the current message. In this case we expected an "xml" formatted message and we also expected a response from the "double" command.
If these conditions are satisfied we can finally output the result in the text area.


SUMMING UP

We've seen that writing server side extensions is very simple and it takes basically three steps:

» send the request object from the client;
» handle the request on the server side and reply to the client;
» handle the server response back to the client.

In the next tutorials we will see how to add database connections, handle server events, create custom login procedures, use optimized protocols and more...


    
 
 
Name: Marco Lapi, a.k.a Lapo
Location: Fossano, Italy
Age: 34
Flash experience: started out with Flash 4 back in 1999
Job: web designer/developer
Website: http://www.gotoandplay.it/
 
 
| Homepage | News | Games | Articles | Multiplayer Central | Reviews | Spotlight | Forums | Info | Links | Contact us | Advertise | Credits |

| www.smartfoxserver.com | www.gotoandplay.biz | www.openspace-engine.com |

gotoAndPlay() v 3.0.0 -- (c)2003-2008 gotoAndPlay() Team -- P.IVA 03121770048