SmartFox

Kind of class:public class
Package:com.smartfoxserver.v2
Inherits from:EventDispatcher
Version:0.9.x
Author:The gotoAndPlay() Team
http://www.smartfoxserver.com
http://www.gotoandplay.it
Classpath:com.smartfoxserver.v2.SmartFox
File last modified:Thursday, 12 August 2010, 15:45:22
SmartFox is the main class in the SmartFoxServer 2X API.
This class is responsible for connecting to the Server and dispatching all asynchronous events.

NOTE: in the provided examples, smartFox always indicates a SmartFox instance.

Summary


Constructor
  • SmartFox (debug:Boolean = false)
    • The SmartFox contructor.
Instance properties
  • isConnected : Boolean
    • Returns true if the client connection is active
  • version : String
    • Return the API current version
  • config : ConfigData
    • Get the current client configuration.
  • compressionThreshold : int
    • Return the current compression threshold: the value represent the maximum message size (in bytes) before the protocol compression is activated.
  • debug : Boolean
    • When set to true provides detailed debugging data for all incoming/outgoing messages
  • currentIp : String
    • The address where the client is connected (if the client is connected)
  • currentPort : int
    • The TCP port of the server where the client is connected (if the client is connected)
  • currentZone : String
    • The current Zone in use, if user is logged in
  • mySelf : User
    • This User object represents the User connected to SmartFoxServer 2X
  • logger : Logger
    • Get a reference to the logger
  • lastJoinedRoom : Room
    • Return the last joined Room, if any.
  • joinedRooms : Array
    • Returns a list of Rooms currently joined by the client
  • roomList : Array
    • Returns the list of Rooms currently "watched" by the client.
  • roomManager : IRoomManager
    • Returns the Room Manager.
  • userManager : IUserManager
    • Returns the User Manager.
  • buddyManager : IBuddyManager
    • Returns the Buddy Manager.
  • udpAvailable : Boolean
    • UPD Protocol is available for AIR 2.0 Runtime and higher
  • udpInited : Boolean
    • Return true if the UDP handshake has been performed successfully
  • sessionToken : String
    • Return the unique session token.
Instance methods
  • getRoomById (id:int) : Room
    • Finds a Room from its Id or returns null if no Room with that Id exist in the room list
  • getRoomByName (name:String) : Room
    • Finds a Room from its name or returns null if no Room with that name exist in the room list
  • getRoomListFromGroup (groupId:String) : Array
    • Return the lis of Rooms from a specific Room Group
  • killConnection : void
    • Simulate an abrupt disconnection
  • connect (host:String = null, port:int = -1) : void
    • Establish connection with SmartFoxServer 2X.
  • disconnect : void
    • Disconnect from SmartFoxServer.
  • initUDP (manager:IUDPManager, udpHost:String = null, udpPort:int = -1) : void
    • Initialize the UDP protocol by starting an handshake with the server.
  • send (request:IRequest) : void
    • Sends a request to the Server.
  • loadConfig (filePath:String = "sfs-config.xml", connectOnSuccess:Boolean = true) : void
    • Load a client configuration file.

Constructor

SmartFox

public function SmartFox (
debug:Boolean = false)

The SmartFox contructor.
Parameters:
debug:
turn on the debug messages (optional).
Example:
  • The following example shows how to instantiate the SmartFox class enabling the debug messages.
    var smartFox:SmartFox = new SmartFox(true)

Instance properties

buddyManager

public buddyManager:IBuddyManager
(read)

Returns the Buddy Manager.
See also:

compressionThreshold

public compressionThreshold:int
(read)

Return the current compression threshold: the value represent the maximum message size (in bytes) before the protocol compression is activated.
The value is determined by the server configuration.

config

public config:ConfigData
(read)

Get the current client configuration. It can return null if the configuration was not loaded
See also:

currentIp

public currentIp:String
(read)

The address where the client is connected (if the client is connected)
See also:

currentPort

public currentPort:int
(read)

The TCP port of the server where the client is connected (if the client is connected)
See also:

currentZone

public currentZone:String
(read)

The current Zone in use, if user is logged in

debug

public debug:Boolean
(read,write)

When set to true provides detailed debugging data for all incoming/outgoing messages

isConnected

public isConnected:Boolean
(read)

Returns true if the client connection is active

joinedRooms

public joinedRooms:Array
(read)

Returns a list of Rooms currently joined by the client
See also:
  • JoinRequest

lastJoinedRoom

public lastJoinedRoom:Room
(read,write)

Return the last joined Room, if any. Null is returned if there's no currently joined Room
See also:
  • JoinRequest

logger

public logger:Logger
(read)

Get a reference to the logger
Returns:
  • the logger

mySelf

public mySelf:User
(read,write)

This User object represents the User connected to SmartFoxServer 2X
The object is generated upon successful login.
See also:

roomList

public roomList:Array
(read)

Returns the list of Rooms currently "watched" by the client.
The list will contain all the Rooms that are currently joined and all the Rooms from the Room Groups that are subscribed.
At login time the User is automatically subscribed to all Room Groups specified in the Zone's Default Groups setting

roomManager

public roomManager:IRoomManager
(read)

Returns the Room Manager.
See also:

sessionToken

public sessionToken:String
(read)

Return the unique session token.
The Session token is a String sent by the server to the client after the initial handshake

udpAvailable

public udpAvailable:Boolean
(read)

UPD Protocol is available for AIR 2.0 Runtime and higher
The method returns true if the current runtime supports UDP.

Using the UDP protocol in an application requires that a handshake is performed between client and server.
By default This is NOT done by the API to avoid allocating resources that might never be used

In order to activate the UDP support you will have to explicitly invoke the initUDP method.
See also:

udpInited

public udpInited:Boolean
(read)

Return true if the UDP handshake has been performed successfully
See also:

userManager

public userManager:IUserManager
(read)

Returns the User Manager.
See also:

version

public version:String
(read)

Return the API current version

Instance methods

connect

public function connect (
host:String = null, port:int = -1) : void

Establish connection with SmartFoxServer 2X.
If not argument is passed the client will use the settings loaded via loadConfig
Parameters:
host:
the address of the server to connect to
port:
the TCP port (default port used by SFS2X is 9933)
Throws:
  • ArgumentError if an invalid host/address or port is passed
See also:

disconnect

public function disconnect (
) : void

Disconnect from SmartFoxServer.

getRoomById

public function getRoomById (
id:int) : Room

Finds a Room from its Id or returns null if no Room with that Id exist in the room list
See also:

getRoomByName

public function getRoomByName (
name:String) : Room

Finds a Room from its name or returns null if no Room with that name exist in the room list
See also:

getRoomListFromGroup

public function getRoomListFromGroup (
groupId:String) : Array

Return the lis of Rooms from a specific Room Group
Parameters:
groupId:
the name of the Group
Returns:
  • the list of rooms
See also:

initUDP

public function initUDP (
manager:IUDPManager, udpHost:String = null, udpPort:int = -1) : void

Initialize the UDP protocol by starting an handshake with the server.
In Flash/Flex the UDP protocol is available exclusively for the AIR 2.0 runtime (or higher)
In order to properly activate the UDP support for the AIR runtime you will need to provide an instance of the custom UDPManager class for AIR provided with the SmartFoxServer 2X API

This method needs to be called only once. It can be executed at any moment provided that you already started connection to the server.
After a successful initialization you can send UDP extension request at any moment.

MTU Note:


The MTU or Maximum Transmission Unit, represents the largest amount of bytes that can be sent at once before packet fragmentation occurs.
Since the UDP protocol uses a "nothing-or-all" appraoch to the transmission, it is important to keep in mind that on average a size of 1100-1200 bytes is probably the maximum you can reach.
If you exceed the MTU size the data will be "lost in hyperspace" (the internet).

Another interesting matter is that there's no fixed size for the MTU, each operating system uses a slighlty different size.
Because of this we suggest a conservative data size of 1000-1200 bytes per packet to avoid packet loss.
The SFS2X protocol compression allows to send 2-3KBytes of uncompressed data which usually is squeezed down to a size of ~1000 bytes.

If you have larger data to send we suggest to organize it in smaller chunks so that they don't exceed the suggested MTU size.

More details about the MTU are found here: http://en.wikipedia.org/wiki/Maximum_transmission_unit
Example:
  • Here is an example of usage:

    smartFox.addEventListener(SFSEvent.UDP_INIT, onUDPInit)
    smartFox.initUDP(new AirUDPManager())
    
    private function onUDPInit(evt:SFSEvent):void
    {
        if (evt.params.success)
        {
        // Execute an extension call via UDP
            smartFox.send( new ExtensionRequest("udpTest", new SFSObject(), null, true) )
    }
        else
        {
            trace("UDP init failed!")
        }
    }

killConnection

public function killConnection (
) : void

Simulate an abrupt disconnection
For testing/simulations only!!!

loadConfig

public function loadConfig (
filePath:String = "sfs-config.xml", connectOnSuccess:Boolean = true) : void

Load a client configuration file.
The SmartFox instance can be configured through an external xml configuration file loaded at run-time.
By default, the loadConfig method loads a file named "sfs-config.xml", placed in the same folder of the application swf file.
If the autoConnect parameter is set to true, on loading completion the connect method is automatically called by the API, otherwise the SFSEvent.onConfigLoadSuccess event is dispatched.
In case of loading error, the SFSEvent.onConfigLoadFailure event id fired.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).
Parameters:
filePath :
external xml configuration file name (optional).
connectOnSuccess:
a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion (optional).
Usage note:
  • The external xml configuration file has the following structure; ip, port and zone parameters are mandatory, all other parameters are optional.
    <SmartFoxClient>
        <ip>127.0.0.1</ip>
        <port>9339</port>
        <zone>simpleChat</zone>
        <debug>true</debug>
        <blueBoxIpAddress>127.0.0.1</blueBoxIpAddress>
        <blueBoxPort>9339</blueBoxPort>
        <smartConnect>true</smartConnect>
        <httpPort>8080</httpPort>
        <httpPollSpeed>750</httpPollSpeed>
        <rawProtocolSeparator>%</rawProtocolSeparator>
    </SmartFoxClient>
Example:
  • The following example shows how to load an external configuration file.
    smartFox.addEventListener(SFSEvent.CONFIG_LOAD_SUCCESS, onConfigLoadSuccessHandler)
    smartFox.addEventListener(SFSEvent.CONFIG_LOAD_FAILURE, onConfigLoadFailureHandler)
    
    smartFox.loadConfig("testEnvironmentConfig.xml", false)
    
    function onConfigLoadSuccessHandler(evt:SFSEvent):void
    {
        trace("Config file loaded, now connecting...")
        smartFox.connect(smartFox.ipAddress, smartFox.port)
    }
    
    function onConfigLoadFailureHandler(evt:SFSEvent):void
    {
        trace("Failed loading config file: " + evt.params.message)
    }

send

public function send (
request:IRequest) : void

Sends a request to the Server.
All the available request objects are found under the requests package.
Parameters:
request:
a request object
Example:
  • This example shows how to send a login request
    smartFox.send( new LoginRequest("KermitTheFrog", "KermitPass", "TheMuppetZone") )
  • This example shows how to send a JoinRoom request
    smartFox.send( new JoinRoomRequest("Lobby") )
  • The following example shows how to send a custom extension request
    var params:ISFSObject = SFSObject.newInstance()
    smartFox.send( new ExtensionRequest("MyExt", params) )