5.b Appendix: Flex 2.0 Application code template

The source of this example is available in the Examples/AS3/SFSTemplate folder.

» Introduction

In this article we will take a look at a simple code template that can be used as a starting point for almost any SmartFoxServer based multiuser application, using Flex Builder 2.
The template is made up of two parts, a simple MXML file called SFSTemplate.mxml and an Actionscript 3.0 file called main.as (the "code behind")

It is required that you're already familiar at least with the "Connection" (5.1) and "Simple Chat" (5.2) tutorials before you proceed with this article.

» The basic steps

One of the problem that developers may find when taking their first steps in multiuser applications, is to fully understand the basic operations that are necessary to interact with the server. In fact there's a precise sequence of commands that is used to establish the connection with the server, before you can fully interact with it.

The sequence is very simple, and looks like this:

1) Establish a socket connection: this is the very first step. At this point it is just like if you were knocking at the server's door.
If the server is up and running it will immediately respond and activate a new communication channel for your client application.

2) Login: in this phase you should tell the server who you are and which application you would like to interact with.
If this operation is successfull you will receive the list of rooms available in the current zone/application.

3) Join a room: this is the last step. Once a room is joined you can start interacting with the other users and the application logic.

» The code

Here's the code of the application-template. For brevity we have stripped the comments that you will find them in the source files.

SFSTemplate.mxml:

 <?xml version="1.0" encoding="utf-8"?>
   <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
   layout="absolute" 
   creationComplete="main()">

  <mx:Script source="main.as" />
  
  <mx:VBox top="20" bottom="20" left="20" right="20" width="100%" height="100%">
  
  <mx:Label 	text="SmartFoxServer Actionscript 3.0 client side template" 
   fontWeight="bold" 
   fontSize="12" 
   color="#000000" />
  
  <mx:TextArea id="ta_debug" width="100%" height="100%" />
  
  <mx:Spacer height="10" />
  <mx:HBox width="100%" horizontalAlign="center">
  <mx:Button 	id="bt_connect" 
   label="CONNECT" 
   width="200" 
   click="bt_connect_click(event)" 
   toolTip="Start the connection with the server" />
  </mx:HBox>
  
  </mx:VBox>
 </mx:Application>

main.as:

import it.gotoandplay.smartfoxserver.SmartFoxClient;
import it.gotoandplay.smartfoxserver.SFSEvent;
import flash.events.Event;

private const NEWLINE:String = "\n";
private var sfs:SmartFoxClient;

public function main():void
{
	sfs = new SmartFoxClient(true);
	
	// Register for SFS events
	sfs.addEventListener(SFSEvent.onConnection, onConnection);
	sfs.addEventListener(SFSEvent.onConnectionLost, onConnectionLost);
	sfs.addEventListener(SFSEvent.onLogin, onLogin);
	sfs.addEventListener(SFSEvent.onRoomListUpdate, onRoomListUpdate);
	sfs.addEventListener(SFSEvent.onJoinRoom, onJoinRoom);
	sfs.addEventListener(SFSEvent.onJoinRoomError, onJoinRoomError);
	
	// Register for generic errors
	sfs.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError)
	sfs.addEventListener(IOErrorEvent.IO_ERROR, onIOError)
	
	debugTrace("Click the CONNECT button to start");
}

public function bt_connect_click(evt:Event):void
{
	if (!sfs.isConnected)
		sfs.connect("127.0.0.1");
	else
		debugTrace("You are already connected!");
}

public function onConnection(evt:SFSEvent):void
{
	var success:Boolean = evt.params.success;
	
	if (success)
	{
		debugTrace("Connection successfull!");
		// Attempt to log in "simpleChat" Zone as a guest user
		sfs.login("simpleChat", "", "");
	}
	else
	{
		debugTrace("Connection failed!");	
	}
}

public function onConnectionLost(evt:SFSEvent):void
{
	debugTrace("Connection lost!");
}

public function onLogin(evt:SFSEvent):void
{
	if (evt.params.success)
	{
		debugTrace("Successfully logged in");
	}
	else
	{
		debugTrace("Login failed. Reason: " + evt.params.error);
	}
}

public function onRoomListUpdate(evt:SFSEvent):void
{
	debugTrace("Room list received");
	
	// Tell the server to auto-join us in the default room for this Zone
	sfs.autoJoin();
}

public function onJoinRoom(evt:SFSEvent):void
{
	debugTrace("Successfully joined room: " + evt.params.room.getName());
}

public function onJoinRoomError(evt:SFSEvent):void
{
	debugTrace("Problems joining default room. Reason: " + evt.params.error);	
}

public function onSecurityError(evt:SecurityErrorEvent):void
{
	debugTrace("Security error: " + evt.text);
}

public function onIOError(evt:IOErrorEvent):void
{
	debugTrace("I/O Error: " + evt.text);
}

public function debugTrace(msg:String):void
{
	ta_debug.text += "--> " + msg + NEWLINE;
}


The three steps that we have highlighted in the introduction are easily recognizable:

1) Establish a socket connection: it is done by calling the connect() method and it is handled in the onConnection() function.

2) Login: the sendLogin() method sends the zone name and an empty user-name. This the simplest form of login: the client is treated as a "guest" and he will be assigned an automatically generated nickname. The login response is received by the onLogin() handler

NOTE: the login process is completely customizable using server side extensions, we have chosen the "guest login" system for the sake of simplicity.

3) Join a room: Finally a room is joined with the join() or autoJoin() method and the result is handled in the onJoinRoom() / on JoinRoomError() functions.

» Handling errors

As you may have noticed, we also registered for the IOErrorEvent and SecurityErrorEvent in order to trap possible I/O errors or Flash Player sandbox security exceptions.

» Importing the example in Flex Builder 2

Here's a step by step guide on how to import the template in your Flex Builder 2 and test it:

1- Choose File > Import

step1

2- Import an existing project

step2

3- Locate the example on your local disk and import it

step3

4- Open the project properties panel

step4

5- Add the SmartFoxClient library to the builder path
Choose "Flex Build Path", click the "Add SWC..." button and point to the SmartFoxClient_AS3.swc file on your local disk.
Then click OK and you're ready to Debug or Run the template application.

step5


doc index