SmartFoxClient

Kind of class:class
Inherits from:XMLSocket
Version:1.5.8
Author:The gotoAndPlay() Team
http://www.smartfoxserver.com
http://www.gotoandplay.it
Classpath:it.gotoandplay.smartfoxserver.SmartFoxClient
File last modified:Tuesday, 21 April 2009, 08:49:49
SmartFoxClient is the main class in the SmartFoxServer API.
This class is responsible for connecting to the server and handling all related events.
Usage:
  • The following example show to instantiate the SmartFoxClient class and how to register an event handler.
    import it.gotoandplay.smartfoxserver.SmartFoxClient
    
    // Create instance
    var smartFox:SmartFoxClient = new SmartFoxClient()
    
    // Add event handler for connection 
    smartFox.onConnection = onConnectionHandler
    
    // Connect to server
    smartFox.connect("127.0.0.1", 9339)
    
    // Handle connection event
    function onConnectionHandler(success:Boolean):Void
    {
        if (success)
            trace("Connection successful")
        else
            trace("Connection failed")
    }
    NOTE: in the following examples, smartFox always indicates a SmartFoxClient instance.
Events broadcasted to listeners:
  • Object with type: onConfigLoadSuccess
  • Object with type: onConfigLoadFailure

Summary


Constructor
Class properties
Instance properties
  • ipAddress : String
    • The SmartFoxServer IP address.
  • port : Number
    • The SmartFoxServer connection port.
  • defaultZone : String
    • The default login zone.
  • httpPort : Number
    • The TCP port used by the embedded webserver.
  • roomList : Object
    • The list of rooms in the current zone.
  • buddyList : Array
    • An array containing the objects representing each buddy of the user's buddy list.
  • myBuddyVars : Array
    • The current user's Buddy Variables.
  • activeRoomId : Number
    • The property stores the id of the last room joined by the current user.
  • myUserId : Number
    • The current user's SmartFoxServer id.
  • myUserName : String
    • The current user's SmartFoxServer username.
  • debug : Boolean
    • Toggle the client-side debugging informations.
  • playerId : Number
    • The current user's id as a player in a game room.
  • amIModerator : Boolean
    • A boolean flag indicating if the user is recognized as Moderator.
  • rawProtocolSeparator : String
    • Get/set the character used as separator for the String (raw) protocol.
  • blueBoxIpAddress : String
    • The BlueBox IP address.
  • blueBoxPort : Number
    • The BlueBox connection port.
  • smartConnect : Boolean
    • A boolean flag indicating if the BlueBox http connection should be used in case a socket connection is not available.
  • socketConnectionTimeout : Number
    • The amount of milliseconds to wait before attempting a BlueBox connection.
  • httpPollSpeed : Number
    • The minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.
Instance methods
  • loadConfig (configFile:String, autoConnect:Boolean) : Void
    • Load a client configuration file.
  • getVersion : String
    • Get the SmartFoxServer Flash API version.
  • connected : Boolean
    • Get the connection status.
  • getConnectionMode : String
    • Get the current connection mode.
  • sendXtMessage (xtName:String, cmdName:String, paramObj, type:String, roomId:Number) : Void
    • Send a request to a server side extension.
  • login (zone:String, name:String, pass:String) : Void
    • Perform the default login procedure.
  • logout : Void
    • Log the user out of the current zone.
  • getRoomList : Void
    • Retrieve the updated list of rooms in the current zone.
  • autoJoin : Void
    • Automatically join the the default room (if existing) for the current zone.
  • joinRoom (newRoom, pword:String, isSpectator:Boolean, dontLeave:Boolean, oldRoom:Number) : Void
    • Join a room.
  • sendBuddyPermissionResponse (allowBuddy:Boolean, targetBuddy:String) : Void
    • Grant current user permission to be added to a buddy list.
  • sendPublicMessage (message:String, roomId:Number) : Void
    • Send a public message.
  • sendPrivateMessage (message:String, recipientId:Number, roomId:Number) : Void
    • Send a private message to a user.
  • sendModeratorMessage (message:String, type:String, id:Number) : Void
    • Send a Moderator message to the current zone, the current room or a specific user in the current room.
  • sendObject (obj:Object, roomId:Number) : Void
    • Send an Actionscript object to the other users in the current room.
  • sendObjectToGroup (obj:Object, userList:Array, roomId:Number) : Void
    • Send an Actionscript object to a group of users in the room.
  • setBuddyBlockStatus (buddyName:String, status:Boolean) : Void
    • Block or unblock a user in the buddy list.
  • setUserVariables (varObj:Object, roomId:Number) : Void
    • Set on or more User Variables.
  • setBuddyVariables (varList:Object) : Void
    • Set the current user's Buddy Variables.
  • createRoom (roomObj:Object, roomId:Number) : Void
    • Dynamically create a new room in the current zone.
  • leaveRoom (roomId:Number) : Void
    • Disconnect the user from the given room.
  • getRoom (roomId) : Room
    • Get a Room object, using its id or name as key.
  • getActiveRoom : Room
    • Get the currently active Room object.
  • setRoomVariables (varList:Array, roomId:Number, setOwnership:Boolean) : Void
    • Set one or more Room Variables.
  • loadBuddyList : Void
    • Load the buddy list for the current user.
  • addBuddy (buddyName:String) : Void
    • Add a user to the buddy list.
  • removeBuddy (buddyName:String) : Void
    • Remove a buddy from the buddy list.
  • getBuddyByName (buddyName:String) : Object
    • Get a buddy from the buddy list, using the buddy's username as key.
  • getBuddyById (id:Number) : Object
    • Get a buddy from the buddy list, using the user id as key.
  • getBuddyRoom (buddy:Object) : Void
    • Request the room id(s) of the room(s) where a buddy is currently located into.
  • clearBuddyList : Void
    • Remove all users from the buddy list.
  • roundTripBench : Void
    • Send a roundtrip request to the server to test the connection' speed.
  • switchSpectator (roomId:Number) : Void
    • Turn a spectator inside a game room into a player.
  • switchPlayer (roomId:Number) : Void
    • Turn a player inside a game room into a spectator.
  • getRandomKey : Void
    • Retrieve a random string key from the server.
  • uploadFile (fileRef, id:Number, nick:String, port:Number) : Void
    • Upload a file to the embedded webserver.
  • getUploadPath : String
    • Get the default upload path of the embedded webserver.
  • connect (ipAdr:String, port:Number) : Void
    • Establish a connection to SmartFoxServer.
  • disconnect : Void
    • Close the current connection to SmartFoxServer.
Event handlers
  • onConnection : Function
    • Called when a response to the connect request is received.
  • onConnectionLost : Function
    • Called when the connection with SmartFoxServer is closed (either from the client or from the server).
  • onCreateRoomError : Function
    • Called when an error occurs during the creation of a room.
  • onJoinRoom : Function
    • Called when a room is joined successfully.
  • onJoinRoomError : Function
    • Called when an error occurs while joining a room.
  • onLogin : Function
    • Called when the login to a SmartFoxServer zone has been attempted.
  • onLogout : Function
    • Called when the user logs out successfully.
  • onObjectReceived : Function
    • Called when an Actionscript object is received.
  • onPublicMessage : Function
    • Called when a public chat message is received.
  • onPrivateMessage : Function
    • Called when a private chat message is received.
  • onAdminMessage : Function
    • Called when a message from the Administrator is received.
  • onModeratorMessage : Function
    • Called when a message from a Moderator is received.
  • onRoomAdded : Function
    • Called when a new room is created in the zone where the user is currently logged in.
  • onRoomDeleted : Function
    • Called when a room is removed from the zone where the user is currently logged in.
  • onRoomLeft : Function
    • Called when a room is left in multi-room mode, after a response to a leaveRoom request is received.
  • onRoomListUpdate : Function
    • Called when the list of rooms available in the current zone is received.
  • onRoomVariablesUpdate : Function
    • Called when Room Variables are updated.
  • onRoundTripResponse : Function
    • Called when a response to the roundTripBench request is received.
  • onUserCountChange : Function
    • Called when the number of users and/or spectators changes in a room within the current zone.
  • onUserEnterRoom : Function
    • Called when another user joins the current room.
  • onUserLeaveRoom : Function
    • Called when a user leaves the current room.
  • onUserVariablesUpdate : Function
    • Called when a user in the current room updates his/her User Variables.
  • onExtensionResponse : Function
    • Called when a command/response from a server-side extension is received.
  • onSpectatorSwitched : Function
    • Called when a response to the switchSpectator request is received.
  • onPlayerSwitched : Function
    • Called in response to the switchPlayer request.
  • onBuddyList : Function
    • Called when the buddy list for the current user is received or a buddy is added/removed.
  • onBuddyListUpdate : Function
    • Called when the status or variables of a buddy in the buddy list change.
  • onBuddyListError : Function
    • Called when an error occurs while loading the buddy list.
  • onBuddyRoom : Function
    • Called when a response to a getBuddyRoom request is received.
  • onBuddyPermissionRequest : Function
    • Called when the current user receives a request to be added to the buddy list of another user.
  • onRandomKey : Function
    • Called when a response to a getRandomKey request is received.
  • onConfigLoadFailure : Function
    • Called when an error occurs while loading the external SmartFoxClient configuration file.
  • onConfigLoadSuccess : Function
    • Called when the external SmartFoxClient configuration file has been loaded successfully.

Constructor

SmartFoxClient

function SmartFoxClient (
objRef:Object)

The SmartFoxClient contructor.
Parameters:
objRef:
a custom parameter to keep a reference to a parent object (optional).
Example:
  • The following example shows how to instantiate the SmartFoxClient class.
    var smartFox:SmartFoxServer = new SmartFoxServer()

Class properties

CONNECTION_MODE_DISCONNECTED

static CONNECTION_MODE_DISCONNECTED:String = "disconnected"
(read,write)

Connection mode: "disconnected".
The client is currently disconnected from SmartFoxServer.
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

CONNECTION_MODE_HTTP

static CONNECTION_MODE_HTTP:String = "http"
(read,write)

Connection mode: "http".
The client is currently connected to SmartFoxServer via http.
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

CONNECTION_MODE_SOCKET

static CONNECTION_MODE_SOCKET:String = "socket"
(read,write)

Connection mode: "socket".
The client is currently connected to SmartFoxServer via socket.
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

MODMSG_TO_ROOM

static MODMSG_TO_ROOM:String = "r"
(read,write)

Moderator message type: "to room".
The Moderator message is sent to all the users in a room.
Version:
  • SmartFoxServer Basic / Pro

MODMSG_TO_USER

static MODMSG_TO_USER:String = "u"
(read,write)

Moderator message type: "to user".
The Moderator message is sent to a single user.
Version:
  • SmartFoxServer Basic / Pro

MODMSG_TO_ZONE

static MODMSG_TO_ZONE:String = "z"
(read,write)

Moderator message type: "to zone".
The Moderator message is sent to all the users in a zone.
Version:
  • SmartFoxServer Basic / Pro

PROTOCOL_JSON

static PROTOCOL_JSON:String = "json"
(read,write)

Server-side extension request/response protocol: JSON.
Version:
  • SmartFoxServer Pro

PROTOCOL_STR

static PROTOCOL_STR:String = "str"
(read,write)

Server-side extension request/response protocol: String (aka "raw protocol").
Version:
  • SmartFoxServer Pro

PROTOCOL_XML

static PROTOCOL_XML:String = "xml"
(read,write)

Server-side extension request/response protocol: XML.
Version:
  • SmartFoxServer Pro

Instance properties

activeRoomId

activeRoomId:Number
(read,write)

The property stores the id of the last room joined by the current user.
In most multiuser applications users can join one room at a time: in this case this property represents the id of the current room.
If multi-room join is allowed, the application should track the various id(s) in an array (for example) and this property should be ignored.
Example:
  • The following example shows how to retrieve the current room object (as an alternative to the getActiveRoom method).
    var room:Room = smartFox.getRoom(smartFox.activeRoomId)
    trace("Current room is: " + room.getName())
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

amIModerator

amIModerator:Boolean
(read,write)

A boolean flag indicating if the user is recognized as Moderator.
Example:
  • The following example shows how to check if the current user is a Moderator in the current SmartFoxServer zone.
    if (smartfox.amIModerator)
        trace("I'm a Moderator in this zone")
    else
        trace("I'm a standard user")
Version:
  • SmartFoxServer Basic / Pro

blueBoxIpAddress

blueBoxIpAddress:String
(read,write)

The BlueBox IP address.
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

blueBoxPort

blueBoxPort:Number = 0
(read,write)

The BlueBox connection port.
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

buddyList

buddyList:Array
(read,write)

An array containing the objects representing each buddy of the user's buddy list.
The buddy list can be iterated with a for-in loop, or a specific object can be retrieved by means of the getBuddyById and getBuddyByName methods.

NOTE: this property and all the buddy-related method are available only if the buddy list feature is enabled for the current zone. Check the SmartFoxServer server-side configuration.

Each element in the buddy list is an object with the following properties:
Parameters:
id :
(Number) the buddy id.
name :
(String) the buddy name.
isOnline :
(Boolean) the buddy online status: true if the buddy is online; false if the buddy is offline.
isBlocked:
(Boolean) the buddy block status: true if the buddy is blocked; false if the buddy is not blocked; when a buddy is blocked, SmartFoxServer does not deliver private messages from/to that user.
variables:
(Object) an object with extra properties of the buddy (Buddy Variables); see also setBuddyVariables.
Example:
  • The following example shows how to retrieve the properties of each buddy in the buddy list.
    for (var b:String in smartFox.buddyList)
    {
        var buddy:Object = smartFox.buddyList[b]
    
        // Trace buddy properties
        trace("Buddy id: " + buddy.id)
        trace("Buddy name: " + buddy.name)
        trace("Is buddy online? " + buddy.isOnline ? "Yes" : "No")
        trace("Is buddy blocked? " + buddy.isBlocked ? "Yes" : "No")
    
        // Trace all Buddy Variables
        for (var v:String in buddy.variables)
            trace("\t" + v + " --> " + buddy.variables[v])
    }
Version history:
  • SmartFoxServer Pro v1.6.0 - Buddy's isBlocked property added.
Version:
  • SmartFoxServer Basic (except block status) / Pro

debug

debug:Boolean
(read,write)

Toggle the client-side debugging informations.
When turned on, the developer is able to inspect all server messages that are sent and received by the client in the Flash authoring environment.
This allows a better debugging of the interaction with the server during application developement.
Example:
  • The following example shows how to turn on SmartFoxServer API debugging.
    var smartFox:SmartFoxClient = new SmartFoxClient()
    var runningLocally:Boolean = true
    
    var ip:String
    var port:Number
    
    if (runningLocally)
    {
        smartFox.debug = true
        ip = "127.0.0.1"
        port = 9339
    }
    else
    {
        smartFox.debug = false
        ip = "100.101.102.103"
        port = 9333
    }
    
    smartFox.connect(ip, port)
Version:
  • SmartFoxServer Lite / Basic / Pro

defaultZone

defaultZone:String = ""
(read,write)

The default login zone.
See also:
Version:
  • SmartFoxServer Pro

httpPollSpeed

httpPollSpeed:Number
(read,write)

The minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.
The default value is 750 milliseconds. Accepted values are between 0 and 10000 milliseconds (10 seconds).
Usage note:
  • Which is the optimal value for polling speed?
    A value between 750-1000 ms is very good for chats, turn-based games and similar kind of applications. It adds minimum lag to the client responsiveness and it keeps the server CPU usage low.
    Lower values (200-500 ms) can be used where a faster responsiveness is necessary. For super fast real-time games values between 50 ms and 100 ms can be tried.
    With settings < 200 ms the CPU usage will grow significantly as the http connection and packet wrapping/unwrapping is more expensive than using a persistent connection.
    Using values below 50 ms is not recommended.
Example:
  • The following example shows how to set the polling speed.
    smartFox.httpPollSpeed = 200
See also:
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

httpPort

httpPort:Number = 8080
(read,write)

The TCP port used by the embedded webserver.
The default port is 8080; if the webserver is listening on a different port number, this property should be set to that value.
Example:
  • The following example shows how to retrieve the webserver's current http port.
    trace("HTTP port is: " + smartfox.httpPort)
See also:
Since:
  • SmartFoxServer Pro v1.5.0
Version:
  • SmartFoxServer Basic / Pro

ipAddress

ipAddress:String
(read,write)

The SmartFoxServer IP address.
See also:
Version:
  • SmartFoxServer Pro

myBuddyVars

myBuddyVars:Array
(read,write)

The current user's Buddy Variables.
This is an associative array containing the current user's properties when he/she is present in the buddy lists of other users.
See the setBuddyVariables method for more details.
Example:
  • The following example shows how to read the current user's own Buddy Variables.
    for (var v:String in smartFox.myBuddyVars)
        trace("Variable " + v + " --> " + smartFox.myBuddyVars[v])
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

myUserId

myUserId:Number
(read,write)

The current user's SmartFoxServer id.
The id is assigned to a user on the server-side as soon as the client connects to SmartFoxServer successfully.

NOTE: client-side, the myUserId property is available only after a successful login is performed using the default login procedure.
If a custom login process is implemented, this property must be manually set after the successful login! If not, various client-side modules (SmartFoxBits, RedBox, etc.) may not work properly.
Example:
  • The following example shows how to retrieve the user's own SmartFoxServer id.
    trace("My user ID is: " + smartFox.myUserId)
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

myUserName

myUserName:String
(read,write)

The current user's SmartFoxServer username.

NOTE: client-side, the myUserName property is available only after a successful login is performed using the default login procedure.
If a custom login process is implemented, this property must be manually set after the successful login! If not, various client-side modules (SmartFoxBits, RedBox, etc.) may not work properly.
Example:
  • The following example shows how to retrieve the user's own SmartFoxServer username.
    trace("I logged in as: " + smartFox.myUserName)
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

playerId

playerId:Number
(read,write)

The current user's id as a player in a game room.
The playerId is available only after the user successfully joined a game room. This id is 1-based (player 1, player 2, etc.), but if the user is a spectator or the room is not a game room, its value is -1.
When a user joins a game room, a player id (or "slot") is assigned to him/her, based on the slots available in the room at the moment in which the user entered it; for example:
  • in a game room for 2 players, the first user who joins it becomes player one (playerId = 1) and the second user becomes player two (player = 2);
  • in a game room for 4 players where only player three is missing, the next user who will join the room will be player three (playerId = 3);
NOTE: if multi-room join is allowed, this property contains only the last player id assigned to the user, and so it's useless.
In this case the Room.getMyPlayerIndex method should be used to retrieve the player id for each joined room.
Example:
  • The following example shows how to retrieve the user's own player id.
    trace("I'm player " + smartFox.playerId)
Version:
  • SmartFoxServer Lite / Basic / Pro

port

port:Number
(read,write)

The SmartFoxServer connection port.
See also:
Version:
  • SmartFoxServer Pro

rawProtocolSeparator

rawProtocolSeparator:String = "%"
(read,write)

Get/set the character used as separator for the String (raw) protocol.
The default value is % (percentage character).

NOTE: this separator must match the one set in the SmartFoxServer server-side configuration file through the <RawProtocolSeparator> parameter.
Example:
  • The following example shows how to set the raw protocol separator.
    smartFox.rawProtocolSeparator = "|"
Since:
  • SmartFoxServer Pro v1.5.5
Version:
  • SmartFoxServer Pro

roomList

roomList:Object
(read,write)

The list of rooms in the current zone.
Unlike the getRoomList method, this property returns the list of Room objects already stored on the client, so no request is sent to the server.
Example:
  • The following example shows how to iterate in the room list.
    for (var r:String in smartFox.roomList)
    {
        var room:Room = smartFox.roomList[r]
        trace("Room: " + room.getName())
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

smartConnect

smartConnect:Boolean = true
(read,write)

A boolean flag indicating if the BlueBox http connection should be used in case a socket connection is not available.
The default value is true.
See also:
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

socketConnectionTimeout

socketConnectionTimeout:Number = 5000
(read,write)

The amount of milliseconds to wait before attempting a BlueBox connection.
The default value is 5000 milliseconds.
Example:
  • The following example shows how to set the socket connection timeout.
    smartfox.socketConnectionTimeout = 2000
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

Instance methods

addBuddy

function addBuddy (
buddyName:String) : Void

Add a user to the buddy list.
Since SmartFoxServer Pro 1.6.0, the buddy list feature can be configured to use a basic or advanced security mode (see the SmartFoxServer server-side configuration file).
Check the following usage notes for details on the behavior of the addBuddy method in the two cases.
Parameters:
buddyName:
the name of the user to be added to the buddy list.
Usage note:
  • Basic security mode
    When a buddy is added, if the buddy list is already full, the onBuddyListError handler is called; otherwise the buddy list is updated and the onBuddyList handler is called.
    Advanced security mode
    If the <addBuddyPermission> parameter is set to true in the buddy list configuration section of a zone, before the user is actually added to the buddy list he/she must grant his/her permission.
    The permission request is sent if the user is online only. When the permission is granted, the buddy list is updated and the onBuddyList handler is called.
    If the permission is not granted (or the buddy didn't receive the permission request), the addBuddy method can be called again after a certain amount of time only. This time is set in the server configuration <permissionTimeOut> parameter.
    Also, if the <mutualAddBuddy> parameter is set to true, when user A adds user B to the buddy list, he/she is automatically added to user B's buddy list.
    Lastly, if the buddy list is full, the onBuddyListError handler is called.
Returns:
Example:
  • The following example shows how to add a user to the buddy list.
    smartFox.addBuddy("jack")
Version history:
  • SmartFoxServer Pro v1.6.0 - Buddy list's advanced security mode implemented.
Version:
  • SmartFoxServer Basic (except advanced mode) / Pro

autoJoin

function autoJoin (
) : Void

Automatically join the the default room (if existing) for the current zone.
A default room can be specified in the SmartFoxServer server-side configuration by adding the autoJoin = "true" attribute to one of the <Room> tags in a zone.
When a room is marked as autoJoin it becomes the default room where all clients are joined when this method is called.
Returns:
Example:
  • The following example shows how to join the default room in the current zone.
    smartFox.autoJoin()
Version:
  • SmartFoxServer Lite / Basic / Pro

clearBuddyList

function clearBuddyList (
) : Void

Deprecated In order to avoid conflits with the buddy list advanced security mode implemented since SmartFoxServer Pro 1.6.0, buddies should be removed one by one, by iterating through the buddy list.
Remove all users from the buddy list.
Returns:
  • Nothing. Causes the onBuddyList handler to be called in response.
Example:
  • The following example shows how to clear the buddy list.
    smartFox.clearBuddyList()
Version history:
  • SmartFoxServer Pro v1.6.0 - Method deprecated.
Version:
  • SmartFoxServer Basic / Pro

connect

function connect (
ipAdr:String, port:Number) : Void

Establish a connection to SmartFoxServer.
The client usually gets connected to SmartFoxServer through a socket connection. In SmartFoxServer Pro, if a socket connection is not available and the smartConnect property is set to true, an http connection to the BlueBox module is attempted.
When a successful connection is established, the getConnectionMode can be used to check the current connection mode.
Parameters:
ipAdr:
the SmartFoxServer ip address.
port :
the SmartFoxServer TCP port.
Returns:
  • Nothing. Causes the onConnection handler to be called in response.
Example:
  • The following example shows how to connect to SmartFoxServer.
    smartFox.connect("127.0.0.1", 9339)
Version history:
  • SmartFoxServer Pro v1.6.0 - BlueBox connection attempt in case of socket connection not available.
Version:
  • SmartFoxServer Lite (except BlueBox connection) / Basic (except BlueBox connection) / Pro

connected

function connected (
) : Boolean

Get the connection status.
Returns:
  • A boolean flag indicating if the current user is connected to the server.
Example:
  • The following example shows how to check the connection status.
    trace("My connection status: " + (smartFox.connected() ? "connected" : "not connected"))
Version:
  • SmartFoxServer Basic / Pro

createRoom

function createRoom (
roomObj:Object, roomId:Number) : Void

Dynamically create a new room in the current zone.

NOTE: if the newly created room is a game room, the user is joined automatically upon successful room creation.
Parameters:
roomObj :
an object with the properties described farther on.
roomId :
the id of the room from where the request is originated, in case the application allows multi-room join (optional, default value: activeRoomId).
The roomObj parameter is an object containing the following properties:
name :
(String) the room name.
password :
(String) a password to make the room private (optional, default: none).
maxUsers :
(Number) the maximum number of users that can join the room.
maxSpectators :
(Number) in game rooms only, the maximum number of spectators that can join the room (optional, default value: 0).
isGame :
(Boolean) if true, the room is a game room (optional, default value: false).
exitCurrentRoom:
(Boolean) if true and in case of game room, the new room is joined after creation (optional, default value: true).
uCount :
(Boolean) if true, the new room will receive the onUserCountChange notifications (optional, default recommended value: false).
vars :
(Array) an array of Room Variables, as described in the setRoomVariables method documentation (optional, default: none).
extension :
(Object) which extension should be dynamically attached to the room, as described farther on (optional, default: none).
A Room-level extension can be attached to any room during creation; the extension property in the roomObj parameter is an object with the following properties:
name :
(String) the name used to reference the extension (see the SmartFoxServer server-side configuration).
script :
(String) the file name of the extension script (for Actionscript and Python); if Java is used, the fully qualified name of the extension must be provided. The file name is relative to the root of the extension folder ("sfsExtensions/" for Actionscript and Python, "javaExtensions/" for Java).
Returns:
Example:
  • The following example shows how to create a new room.
    var roomObj:Object = new Object()
    roomObj.name = "The Cave"
    roomObj.isGame = true
    roomObj.maxUsers = 15
    
    var variables:Array = new Array()
    variables.push({name:"ogres", val:5, priv:true})
    variables.push({name:"skeletons", val:4})
    
    roomObj.vars = variables
    
    smartFox.createRoom(roomObj)
Version:
  • SmartFoxServer Lite / Basic / Pro

disconnect

function disconnect (
) : Void

Close the current connection to SmartFoxServer.
Returns:
Example:
  • The following example shows how to disconnect from SmartFoxServer.
    smartFox.disconnect()
Version:
  • SmartFoxServer Lite / Basic / Pro

getActiveRoom

function getActiveRoom (
) : Room

Get the currently active Room object.
SmartFoxServer allows users to join two or more rooms at the same time (multi-room join). If this feature is used, then this method is useless and the application should track the various room id(s) manually, for example by keeping them in an array.
Returns:
  • the Room object of the currently active room; if the user joined more than one room, the last joined room is returned.
Example:
  • The following example shows how to retrieve the current room object.
    var room:Room = smartFox.getActiveRoom()
    trace("Current room is: " + room.getName())
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

getBuddyById

function getBuddyById (
id:Number) : Object

Get a buddy from the buddy list, using the user id as key.
Refer to the buddyList property for a description of the buddy object's properties.
Parameters:
id:
the user id of the buddy.
Returns:
  • The buddy object.
Example:
  • The following example shows how to retrieve a buddy from the buddy list.
    var buddy:Object = smartFox.getBuddyById(25)
    
    trace("Buddy id: " + buddy.id)
    trace("Buddy name: " + buddy.name)
    trace("Is buddy online? " + buddy.isOnline ? "Yes" : "No")
    trace("Is buddy blocked? " + buddy.isBlocked ? "Yes" : "No")
    
    trace("Buddy Variables:")
    for (var v:String in buddy.variables)
        trace("\t" + v + " --> " + buddy.variables[v])
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

getBuddyByName

function getBuddyByName (
buddyName:String) : Object

Get a buddy from the buddy list, using the buddy's username as key.
Refer to the buddyList property for a description of the buddy object's properties.
Parameters:
buddyName:
the username of the buddy.
Returns:
  • The buddy object.
Example:
  • The following example shows how to retrieve a buddy from the buddy list.
    var buddy:Object = smartFox.getBuddyByName("jack")
    
    trace("Buddy id: " + buddy.id)
    trace("Buddy name: " + buddy.name)
    trace("Is buddy online? " + buddy.isOnline ? "Yes" : "No")
    trace("Is buddy blocked? " + buddy.isBlocked ? "Yes" : "No")
    
    trace("Buddy Variables:")
    for (var v:String in buddy.variables)
        trace("\t" + v + " --> " + buddy.variables[v])
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

getBuddyRoom

function getBuddyRoom (
buddy:Object) : Void

Request the room id(s) of the room(s) where a buddy is currently located into.
Parameters:
buddy:
a buddy object taken from the buddyList array.
Returns:
  • Nothing. Causes the onBuddyRoom handler to be called in response.
Example:
  • The following example shows how to join the same room of a buddy.
    smartFox.onBuddyRoom = onBuddyRoomHandler
    
    var buddy:Object = smartFox.getBuddyByName("jack")
    smartFox.getBuddyRoom(buddy)
    
    function onBuddyRoomHandler(idList:Array):Void
    {
        // Reach the buddy in his room
        smartFox.join(idList[0])
    }
Version:
  • SmartFoxServer Basic / Pro

getConnectionMode

function getConnectionMode (
) : String

Get the current connection mode.
Returns:
Example:
  • The following example shows how to check the current connection mode.
        smartFox.onConnection = onConnectionHandler
    
    smartFox.connect("127.0.0.1", 9339)
    
    function onConnectionHandler(success:Boolean):Void
    {
        trace("Connection mode: " + smartFox.getConnectionMode())
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

getRandomKey

function getRandomKey (
) : Void

Retrieve a random string key from the server.
This key is also referred in the SmartFoxServer documentation as the "secret key".
It's a unique key, valid for the current session only. It can be used to create a secure login system.
Returns:
  • Nothing. Causes the onRandomKey handler to be called in response.
Example:
  • The following example shows how to handle the request a random key to the server.
    smartFox.onRandomKey = onRandomKeyHandler
    
    smartFox.getRandomKey()
    
    function onRandomKeyHandler(key:String):Void
    {
        trace("Random key received from server: " + key)
    }
See also:
Version:
  • SmartFoxServer Pro

getRoom

function getRoom (
roomId) : Room

Get a Room object, using its id or name as key.
Parameters:
roomId:
the id (Number) or the name (String) of the room.
Returns:
Example:
  • The following example shows how to retrieve a room from its id.
    var roomObj:Room = smartFox.getRoom(15)
    trace("Room name: " + roomObj.getName() + ", max users: " + roomObj.getMaxUsers())
Version:
  • SmartFoxServer Lite / Basic / Pro

getRoomList

function getRoomList (
) : Void

Retrieve the updated list of rooms in the current zone.
Unlike the roomList property, this method sends a request to the server, which then sends back the complete list of rooms with all their properties and server-side variables (Room Variables).

If the default login mechanism provided by SmartFoxServer is used, then the updated list of rooms is received right after a successful login, without the need to call this method.
Instead, if a custom login handler is implemented, the room list must be manually requested to the server using this method.
Returns:
Example:
  • The following example shows how to retrieve the room list from the server.
    smartFox.onRoomListUpdate = onRoomListUpdateHandler
    
    smartFox.getRoomList()
    
    function onRoomListUpdateHandler(roomList:Object):Void
    {
        // Dump the names of the available rooms in the current zone
        for (var r:String in roomList)
            trace(roomList[r].getName())
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

getUploadPath

function getUploadPath (
) : String

Get the default upload path of the embedded webserver.
Returns:
  • The http address of the default folder in which files are uploaded.
Example:
  • The following example shows how to get the default upload path.
    var path:String = smartFox.getUploadPath()
See also:
Since:
  • SmartFoxServer Pro v1.5.0
Version:
  • SmartFoxServer Basic / Pro

getVersion

function getVersion (
) : String

Get the SmartFoxServer Flash API version.
Returns:
  • The current version of the SmartFoxServer client API.
Example:
  • The following example shows how to trace the SmartFoxServer API version.
    trace("Current API version: " + smartFox.getVersion())
Version:
  • SmartFoxServer Lite / Basic / Pro

joinRoom

function joinRoom (
newRoom, pword:String, isSpectator:Boolean, dontLeave:Boolean, oldRoom:Number) : Void

Join a room.
Parameters:
newRoom :
the name (String) or the id (Number) of the room to join.
pword :
the room's password, if it's a private room (optional, dafault value: null).
isSpectator:
a boolean flag indicating wheter you join as a spectator or not (optional, dafault value: false).
dontLeave :
a boolean flag indicating if the current room must be left after successfully joining the new room (optional, dafault value: false).
oldRoom :
the id of the room to leave (optional, default value: activeRoomId).
NOTE: the last two optional parameters enable the advanced multi-room join feature of SmartFoxServer, which allows a user to join two or more rooms at the same time. If this feature is not required, the parameters can be omitted.
Returns:
Example:
  • In the following example the user requests to join a room with id = 10; by default SmartFoxServer will disconnect him from the previous room.
    smartFox.joinRoom(10)

    In the following example the user requests to join a room with id = 12 and password = "mypassword"; by default SmartFoxServer will disconnect him from the previous room.
    smartFox.joinRoom(12, "mypassword")

    In the following example the user requests to join the room with id = 15 and passes true to the dontLeave flag; this will join the user in the new room while keeping him in the old room as well.
    smartFox.joinRoom(15, "", false, true)
Version:
  • SmartFoxServer Lite / Basic / Pro

leaveRoom

function leaveRoom (
roomId:Number) : Void

Disconnect the user from the given room.
This method should be used only when users are allowed to be present in more than one room at the same time (multi-room join feature).
Parameters:
roomId:
the id of the room to leave.
Returns:
  • Nothing. Causes the onRoomLeft handler to be called in response.
Example:
  • The following example shows how to make a user leave a room.
    smartFox.leaveRoom(15)
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

loadBuddyList

function loadBuddyList (
) : Void

Load the buddy list for the current user.
Returns:
Example:
  • The following example shows how to load the current user's buddy list.
    smartFox.onBuddyList = onBuddyListHandler
    
    smartFox.loadBuddyList()		
    
    function onBuddyListHandler(list:Array):Void
    {
        for (var b:String in list)
        {
            var buddy:Object = list[b]
    
            trace("Buddy id: " + buddy.id)
            trace("Buddy name: " + buddy.name)
            trace("Is buddy online? " + buddy.isOnline ? "Yes" : "No")
            trace("Is buddy blocked? " + buddy.isBlocked ? "Yes" : "No")
    
            trace("Buddy Variables:")
            for (var v:String in buddy.variables)
                trace("\t" + v + " --> " + buddy.variables[v])
        }
    }
Version:
  • SmartFoxServer Basic / Pro

loadConfig

function loadConfig (
configFile:String, autoConnect:Boolean) : Void

Load a client configuration file.
The SmartFoxClient instance can be configured through an external xml configuration file loaded at run-time.
By default, the loadConfig method loads a file named "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 onConfigLoadSuccess handler is called.
In case of loading error, the onConfigLoadFailure handler id called.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).
Parameters:
configFile :
external xml configuration file name (optional).
autoConnect:
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>
        <socketConnectionTimeout>5000</socketConnectionTimeout>
        <httpPort>8080</httpPort>
        <httpPollSpeed>750</httpPollSpeed>
        <rawProtocolSeparator>%</rawProtocolSeparator>
    </SmartFoxClient>
Returns:
Events broadcasted to listeners:
  • Object with type: onConfigLoadSuccess
  • Object with type: onConfigLoadFailure
Example:
  • The following example shows how to load an external configuration file.
    smartFox.onConfigLoadSuccess = onConfigLoadSuccessHandler
    smartFox.onConfigLoadFailure = onConfigLoadFailureHandler
    
    smartFox.loadConfig("testEnvironmentConfig.xml", false)
    
    function onConfigLoadSuccessHandler():Void
    {
        trace("Config file loaded, now connecting...")
        smartFox.connect(smartFox.ipAddress, smartFox.port)
    }
    
    function onConfigLoadFailureHandler(message:String):Void
    {
        trace("Failed loading config file: " + message)
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

login

function login (
zone:String, name:String, pass:String) : Void

Perform the default login procedure.
The standard SmartFoxServer login procedure accepts guest users. If a user logs in with an empty username, the server automatically creates a name for the client using the format guest_n, where n is a progressive number.
Also, the provided username and password are checked against the moderators list (see the SmartFoxServer server-side configuration) and if a user matches it, he is set as a Moderator.

NOTE 1: duplicate names in the same zone are not allowed.

NOTE 2: for SmartFoxServer Basic, where a server-side custom login procedure can't be implemented due to the lack of extensions support, a custom client-side procedure can be used, for example to check usernames against a database using a php/asp page.
In this case, this should be done BEFORE calling the login method. This way, once the client is validated, the stadard login procedure can be used.

NOTE 3: for SmartFoxServer PRO. If the Zone you are accessing uses a custom login the login-response will be sent from server side and you will need to handle it using the onExtensionResponse handler.
Additionally you will need to manually set the myUserId and myUserName properties if you need them. (This is automagically done by the API when using a default login)
Parameters:
zone:
the name of the zone to log into.
name:
the user name.
pass:
the user password.
Returns:
  • Nothing. Causes the onLogin handler to be called in response.
Example:
  • The following example shows how to login into a zone.
    smartFox.onLogin = onLoginHandler
    
    smartFox.login("simpleChat", "jack")
    
    function onLoginHandler(response:Object):Void
    {
        if (response.success)
            trace("Successfully logged in as " + response.name)
        else
            trace("Zone login error; the following error occurred: " + response.error)
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

logout

function logout (
) : Void

Log the user out of the current zone.
After a successful logout the user is still connected to the server, but he/she has to login again into a zone, in order to be able to interact with the server.
Returns:
  • Nothing. Causes the onLogout handler to be called in response.
Example:
  • The following example shows how to logout from a zone.
    smartFox.onLogout = onLogoutHandler
    
    smartFox.logout()
    
    function onLogoutHandler():Void
    {
        trace("Logged out successfully")
    }
See also:
Since:
  • SmartFoxServer Pro v1.5.5
Version:
  • SmartFoxServer Basic / Pro

removeBuddy

function removeBuddy (
buddyName:String) : Void

Remove a buddy from the buddy list.
Since SmartFoxServer Pro 1.6.0, the buddy list feature can be configured to use a basic or advanced security mode (see the SmartFoxServer server-side configuration file).
Check the following usage notes for details on the behavior of the removeBuddy method in the two cases.
Parameters:
buddyName:
the name of the user to be removed from the buddy list.
Usage note:
  • Basic security mode
    When a buddy is removed, the buddy list is updated and the onBuddyList handler is called.
    Advanced security mode
    In addition to the basic behavior, if the <mutualRemoveBuddy> server-side configuration parameter is set to true, when user A removes user B from the buddy list, he/she is automatically removed from user B's buddy list.
Returns:
  • Nothing. Causes the onBuddyList handler to be called in response.
Example:
  • The following example shows how to remove a user from the buddy list.
    var buddyName:String = "jack"
    smartFox.removeBuddy(buddyName)
Version history:
  • SmartFoxServer Pro v1.6.0 - Buddy list's advanced security mode implemented.
Version:
  • SmartFoxServer Basic (except advanced mode) / Pro

roundTripBench

function roundTripBench (
) : Void

Send a roundtrip request to the server to test the connection' speed.
The roundtrip request sends a small packet to the server which immediately responds with another small packet, and causing the onRoundTripResponse handler to be called.
The time taken by the packet to travel forth and back is called "roundtrip time" and can be used to calculate the average network lag of the client.
A good way to measure the network lag is to send continuos requests (every 3 or 5 seconds) and then calculate the average roundtrip time on a fixed number of responses (i.e. the last 10 measurements).
Returns:
Example:
  • The following example shows how to check the average network lag time.
    smartFox.onRoundTripResponse = onRoundTripResponseHandler
    
    var totalPingTime:Number = 0
    var pingCount:Number = 0
    
    smartFox.roundTripBench() // TODO: this method must be called repeatedly every 3-5 seconds to have a significant average value
    
    function onRoundTripResponseHandler(elapsed:Number):Void
    {
        // We assume that it takes the same time to the ping message to go from the client to the server
        // and from the server back to the client, so we divide the elapsed time by 2.
        totalPingTime += elapsed / 2
        pingCount++
    
        var avg:Number = Math.round(totalPingTime / pingCount)
    
        trace("Average lag: " + avg + " milliseconds")
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

sendBuddyPermissionResponse

function sendBuddyPermissionResponse (
allowBuddy:Boolean, targetBuddy:String) : Void

Grant current user permission to be added to a buddy list.
If the SmartFoxServer Pro 1.6.0 advanced security mode is used (see the SmartFoxServer server-side configuration), when a user wants to add a buddy to his/her buddy list, a permission request is sent to the buddy.
Once the onBuddyPermissionRequest handler is called, this method must be used by the buddy to grant or refuse permission. When the permission is granted, the requester's buddy list is updated.
Parameters:
allowBuddy :
true to grant permission, false to refuse to be added to the requester's buddy list.
targetBuddy:
the username of the requester.
Example:
  • The following example shows how to grant permission to be added to a buddy list once request is received.
    smartFox.onBuddyPermissionRequest = onBuddyPermissionRequestHandler
    
    var autoGrantPermission:Boolean = true
    
    function onBuddyPermissionRequestHandler(sender:String, message:String):Void
    {
        if (autoGrantPermission)
        {
            // Automatically grant permission
    
            smartFox.sendBuddyPermissionResponse(true, sender)
        }
        else
        {
            // Display an alert attaching a movieclip from the Flash library
            var alert_mc:MovieClip = attachMovie("customAlertPanel", "customAlertPanel", 100)
    
            alert_mc.name_lb.text = sender
            alert_mc.message_lb.text = message
        }
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

sendModeratorMessage

function sendModeratorMessage (
message:String, type:String, id:Number) : Void

Send a Moderator message to the current zone, the current room or a specific user in the current room.
In order to send these kind of messages, the user must have Moderator's privileges, which are set by SmartFoxServer when the user logs in (see the login method).
Parameters:
message:
the text of the message.
type :
the type of message. The following constants can be passed: MODMSG_TO_USER, MODMSG_TO_ROOM and MODMSG_TO_ZONE, to send the message to a user, to the current room or to the entire current zone respectively.
id :
the id of the recipient room or user (ignored if the message is sent to the zone).
Returns:
Example:
  • The following example shows how to send a Moderator message.
    smartFox.sendModeratorMessage("Greetings from the Moderator", SmartFoxClient.MODMSG_TO_ROOM, smartFox.getActiveRoom())
Since:
  • SmartFoxServer Pro v1.4.5
Version:
  • SmartFoxServer Basic / Pro

sendObject

function sendObject (
obj:Object, roomId:Number) : Void

Send an Actionscript object to the other users in the current room.
This method can be used to send complex/nested data structures to clients, like a game move or a game status change. Supported data types are: Strings, Booleans, Numbers, Arrays, Objects.
Parameters:
obj :
the Actionscript object to be sent.
roomId:
the id of the target room, in case of multi-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to send a simple object with primitive data to the other users.
    var move:Object = new Object()
    move.x = 150
    move.y = 250
    move.speed = 8
    
    smartFox.sendObject(move)

    The following example shows how to send an object with two arrays of items to the other users.
    var itemsFound:Object = new Object()
    itemsFound.jewels = ["necklace", "ring"]
    itemsFound.weapons = ["sword", "sledgehammer"]
    
    smartFox.sendObject(itemsFound)
Version:
  • SmartFoxServer Lite / Basic / Pro

sendObjectToGroup

function sendObjectToGroup (
obj:Object, userList:Array, roomId:Number) : Void

Send an Actionscript object to a group of users in the room.
See sendObject for more info.
Parameters:
obj :
the Actionscript object to be sent.
userList:
an array containing the id(s) of the recipients.
roomId :
the id of the target room, in case of multi-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to send a simple object with primitive data to two users.
    var move:Object = new Object()
    move.x = 150
    move.y = 250
    move.speed = 8
    
    smartFox.sendObjectToGroup(move, [11, 12])
Version:
  • SmartFoxServer Lite / Basic / Pro

sendPrivateMessage

function sendPrivateMessage (
message:String, recipientId:Number, roomId:Number) : Void

Send a private message to a user.
The message is broadcasted to the recipient and the sender.
Parameters:
message :
the text of the private message.
recipientId:
the id of the recipient user.
roomId :
the id of the room from where the message is sent, in case of multi-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to send and receive a private message.
    smartFox.onPrivateMessage = onPrivateMessageHandler
    
    smartFox.sendPrivateMessage("Hallo Jack!", 22)
    
    function onPrivateMessageHandler(message:String, sender:User):Void
    {
        trace("User " + sender.getName() + " sent the following private message: " + message)
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

sendPublicMessage

function sendPublicMessage (
message:String, roomId:Number) : Void

Send a public message.
The message is broadcasted to all users in the current room, including the sender.
Parameters:
message:
the text of the public message.
roomId :
the id of the target room, in case of multi-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to send and receive a public message.
    smartFox.onPublicMessage = onPublicMessageHandler
    
    smartFox.sendPublicMessage("Hello world!")
    
    function onPublicMessageHandler(message:String, sender:User):Void
    {
        trace("User " + sender.getName() + " said: " + message)
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

sendXtMessage

function sendXtMessage (
xtName:String, cmdName:String, paramObj, type:String, roomId:Number) : Void

Send a request to a server side extension.
The request can be serialized using three different protocols: XML, JSON and String-based (aka "raw protocol").
XML and JSON can both serialize complex objects with any level of nested properties, while the String protocol allows to send linear data delimited by a separator (see the rawProtocolSeparator property).

NOTE: the use JSON instead of XML is highly recommended, as it can save a lot of bandwidth. The String-based protocol can be very useful for realtime applications/games where reducing the amount of data is the highest priority.
Parameters:
xtName :
the name of the extension (see also the createRoom method).
cmdName :
the name of the action/command to execute in the extension.
paramObj:
an object containing the data to be passed to the extension (set to empty object if no data is required).
type :
the protocol to be used for serialization (optional, default value: PROTOCOL_XML). The following constants can be passed: PROTOCOL_XML, PROTOCOL_STR, PROTOCOL_JSON.
roomId :
the id of the room where the request was originated, in case of multi-room join (optional, default value: activeRoomId).
Returns:
  • Nothing. May cause the onExtensionResponse handler to be called in response (depending on the extension implementation).
Example:
  • The following example shows how to notify a multiplayer game server-side extension that a game action occurred.
    // A bullet is being fired
    var params:Object = {}
    params.type = "bullet"
    params.posx = 100
    params.posy = 200
    params.speed = 10
    params.angle = 45
    
    // Invoke "fire" command on the extension called "gameExt", using JSON protocol
    smartFox.sendXtMessage("gameExt", "fire", params, SmartFoxClient.PROTOCOL_JSON)
Version:
  • SmartFoxServer Pro

setBuddyBlockStatus

function setBuddyBlockStatus (
buddyName:String, status:Boolean) : Void

Block or unblock a user in the buddy list.
When a buddy is blocked, SmartFoxServer does not deliver private messages from/to that user.
Parameters:
buddyName:
the name of the buddy to be blocked or unblocked.
status :
true to block the buddy, false to unblock the buddy.
Example:
  • The following example shows how to block a user from the buddy list.
    smartFox.setBuddyBlockStatus("jack", true)
See also:
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

setBuddyVariables

function setBuddyVariables (
varList:Object) : Void

Set the current user's Buddy Variables.
This method allows to set a number of properties of the current user as buddy of other users; in other words these variables will be received by the other users who have the current user as a buddy.

Buddy Variables are the best way to share user's informations with all the other users having him/her in their buddy list.: for example the nickname, the current audio track the user is listening to, etc. The most typical usage is to set a variable containing the current user status, like "available", "occupied", "away", "invisible", etc.).

NOTE: before the release of SmartFoxServer Pro v1.6.0, Buddy Variables could not be stored, and existed during the user session only. SmartFoxServer Pro v1.6.0 introduced the ability to persist (store) all Buddy Variables and the possibility to save "offline Buddy Variables" (see the following usage notes).
Parameters:
varList:
an associative array, where the key is the name of the variable and the value is the variable's value. Buddy Variables should all be strings. If you need to use other data types you should apply the appropriate type casts.
Usage note:
  • Let's assume that three users (A, B and C) use an "istant messenger"-like application, and user A is part of the buddy lists of users B and C.
    If user A sets his own variables (using the setBuddyVariables method), the myBuddyVars array on his client gets populated and the onBuddyListUpdate handler is called on the clients of users B and C.
    User B and C can then read those variables in their own buddy lists by means of the variables property on the buddy object (which can be retrieved from the buddyList array by means of the getBuddyById or getBuddyByName methods).
    If the buddy list's advanced security mode is used (see the SmartFoxServer server-side configuration), Buddy Variables persistence is enabled: in this way regular variables are saved when a user goes offline and they are restored (and dispatched to the other users) when their owner comes back online.
    Also, setting the <offLineBuddyVariables> parameter to true, offline variables can be used: this kind of Buddy Variables is loaded regardless the buddy is online or not, providing further informations for each entry in the buddy list. A typical usage for offline variables is to define a buddy image or additional informations such as country, email, rank, etc.
    To creare an offline Buddy Variable, the "$" character must be placed before the variable name.
Returns:
Example:
  • The following example shows how to set three variables containing the user's status, the current audio track the user listening to and the user's rank. The last one is an offline variable.
    var bVars:Object = new Object()
    bVars["status"] = "away"
    bVars["track"] = "One Of These Days"
    bVars["$rank"] = "guru"
    
    smartFox.setBuddyVariables(bVars)
Version history:
  • SmartFoxServer Pro v1.6.0 - Buddy list's advanced security mode implemented (persistent and offline Buddy Variables).
Version:
  • SmartFoxServer Basic (except advanced mode) / Pro

setRoomVariables

function setRoomVariables (
varList:Array, roomId:Number, setOwnership:Boolean) : Void

Set one or more Room Variables.
Room Variables are a useful feature to share data across the clients, keeping it in a centralized place on the server. When a user sets/updates/deletes one or more Room Variables, all the other users in the same room are notified.
Allowed data types for Room Variables are Numbers, Strings and Booleans; in order save bandwidth, Arrays and Objects are not supported. Nevertheless, an array of values can be simulated, for example, by using an index in front of the name of each variable (check one of the following examples).
If a Room Variable is set to null, it is deleted from the server.
Parameters:
varList :
an array of objects with the properties described farther on.
roomId :
the id of the room where the variables should be set, in case of molti-room join (optional, default value: activeRoomId).
setOwnership:
false to prevent the Room Variable change ownership when its value is modified by another user (optional, default value: true).
Each Room Variable is an object containing the following properties:
name :
(String) the variable name.
val :
(any supported data type) the variable value.
priv :
(Boolean) if true, the variable can be modified by its creator only (optional, default value: false).
persistent :
(Boolean) if true, the variable will exist until its creator is connected to the current zone; if false, the variable will exist until its creator is connected to the current room (optional, default value: false).
Returns:
Example:
  • The following example shows how to save a persistent Room Variable called "score". This variable won't be destroyed when its creator leaves the room.
    var rVars:Array = new Array()
    rVars.push({name:"score", val:2500, persistent:true})
    
    smartFox.setRoomVariables(rVars)

    The following example shows how to save two Room Variables at once. The one called "bestTime" is private and no other user except its owner can modify it.
    var rVars:Array = new Array()
    rVars.push({name:"bestTime", val:100, priv:true})
    rVars.push({name:"bestLap", val:120})
    
    smartFox.setRoomVariables(rVars)

    The following example shows how to delete a Room Variable called "bestTime" by setting its value to null.
    var rVars:Array = new Array()
    rVars.push({name:"bestTime", val:null})
    
    smartFox.setRoomVariables(rVars)

    The following example shows how to send an array-like set of data without consuming too much bandwidth.
    var rVars:Array = new Array()
    var names:Array = ["john", "dave", "sam"]
    
    for (var i:Number = 0; i < names.length; i++)
        rVars.push({name:"name" + i, val:names[i]})
    
    smartFox.setRoomVariables(rVars)

    The following example shows how to handle the data sent in the previous example when the onRoomVariablesUpdate handler is called.
    smartFox.onRoomVariablesUpdate = onRoomVariablesUpdateHandler
    
    function onRoomVariablesUpdateHandler(room:Room, changedVars:Array):Void
    {
            // Iterate on the 'changedVars' array to check which variables were updated
            for (var v:String in changedVars)
                trace(v + " room variable was updated; new value is: " + room.getVariable(v))
    }

    The following example shows how to update a Room Variable without affecting the variable's ownership.
    By default, when a user updates a Room Variable, he becomes the "owner" of that variable. In some cases it could be needed to disable this behavoir by setting the setOwnership to false.
    // For example, a variable that is defined in the server-side xml configuration file is owned by the Server itself;
    // if it's not set to private, its owner will change as soon as a user updates it.
    // To avoid this change of ownership the setOwnership flag is set to false.
    var rVars:Array = new Array()
    rVars.push({name:"shipPosX", val:100})
    rVars.push({name:"shipPosY", val:200})
    
    smartFox.setRoomVariables(rVars, smartFox.getActiveRoom(), false)
Version:
  • SmartFoxServer Lite / Basic / Pro

setUserVariables

function setUserVariables (
varObj:Object, roomId:Number) : Void

Set on or more User Variables.
User Variables are a useful tool to store user data that has to be shared with other users. When a user sets/updates/deletes one or more User Variables, all the other users in the same room are notified.
Allowed data types for User Variables are Numbers, Strings and Booleans; Arrays and Objects are not supported in order save bandwidth.
If a User Variable is set to null, it is deleted from the server. Also, User Variables are destroyed when their owner logs out or gets disconnected.
Parameters:
varObj:
an object in which each property is a variable to set/update.
roomId:
the room id where the request was originated, in case of molti-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to save the user data (avatar name and position) in an avatar chat application.
    var uVars:Object = new Object()
    uVars.myAvatar = "Homer"
    uVars.posx = 100
    uVars.posy = 200
    
    smartFox.setUserVariables(uVars)
Version:
  • SmartFoxServer Lite / Basic / Pro

switchPlayer

function switchPlayer (
roomId:Number) : Void

Turn a player inside a game room into a spectator.
All players have their player id property set to a value > 0; when a player becomes a spectator, his playerId is set to -1.
If the user joined more than one room, the id of the room where the switch should occurr must be passed to this method.
The switch operation is successful only if at least one spectator slot is available in the room.
Parameters:
roomId:
the id of the room where the player should be switched to spectator, in case of multi-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to turn a player into a spectator.
    smartFox.onPlayerSwitched = onPlayerSwitchedHandler
    
    smartFox.switchPlayer()
    
    function onPlayerSwitchedHandler(success:Boolean, newId:Number):Void
    {
        if (success)
            trace("You have been turned into a spectator; your id is: " + newId)
        else
            trace("The attempt to switch from player to spectator failed!")
    }
Version:
  • SmartFoxServer Pro

switchSpectator

function switchSpectator (
roomId:Number) : Void

Turn a spectator inside a game room into a player.
All spectators have their player id property set to -1; when a spectator becomes a player, his player id gets a number > 0, representing the player number. The player id values are assigned by the server, based on the order in which the players joined the room.
If the user joined more than one room, the id of the room where the switch should occurr must be passed to this method.
The switch operation is successful only if at least one player slot is available in the room.
Parameters:
roomId:
the id of the room where the spectator should be switched, in case of molti-room join (optional, default value: activeRoomId).
Returns:
Example:
  • The following example shows how to turn a spectator into a player.
    smartFox.onSpectatorSwitched = onSpectatorSwitchedHandler
    
    smartFox.switchSpectator()
    
    function onSpectatorSwitchedHandler(success:Boolean, newId:Number):Void
    {
        if (success)
            trace("You have been turned into a player; your player id is " + newId)
        else
            trace("The attempt to switch from spectator to player failed")
    }
Version:
  • SmartFoxServer Basic / Pro

uploadFile

function uploadFile (
fileRef, id:Number, nick:String, port:Number) : Void

Upload a file to the embedded webserver.
Parameters:
fileRef:
the FileReference object (see the example).
id :
the user id (optional, default value: myUserId).
nick :
the user name (optional, default value: myUserName).
port :
the webserver's TCP port (optional, default value: httpPort).
Returns:
  • Nothing. Upload events fired in response should be handled by the provided FileReference object (see the example).
Example:
Since:
  • SmartFoxServer Pro v1.5.0
Version:
  • SmartFoxServer Basic / Pro

Event handlers

onAdminMessage

onAdminMessage:Function
(read,write)

Called when a message from the Administrator is received.
Admin messages are special messages that can be sent by an Administrator to a user or group of users.
All client applications should implement this handler, or users won't be be able to receive important admin notifications!

The following parameters are passed to this function.
Parameters:
message:
(String) the Administrator's message.
Example:
  • The following example shows how to handle a message coming from the Administrator.
    smartFox.onAdminMessage = onAdminMessageHandler
    
    function onAdminMessageHandler(message:String):Void
    {
        trace("Administrator said: " + message)
    }
Version:
  • SmartFoxServer Basic / Pro

onBuddyList

onBuddyList:Function
(read,write)

Called when the buddy list for the current user is received or a buddy is added/removed.

The following parameters are passed to this function.
Parameters:
list:
(Array) the buddy list. Refer to the buddyList property for a description of the buddy object's properties.
Example:
  • The following example shows how to retrieve the properties of each buddy when the buddy list is received.
    smartFox.onBuddyList = onBuddyListHandler
    
    smartFox.loadBuddyList()		
    
    function onBuddyListHandler(list:Array):Void
    {
        for (var b:String in list)
        {
            var buddy:Object = list[b]
    
            trace("Buddy id: " + buddy.id)
            trace("Buddy name: " + buddy.name)
            trace("Is buddy online? " + buddy.isOnline ? "Yes" : "No")
            trace("Is buddy blocked? " + buddy.isBlocked ? "Yes" : "No")
    
            trace("Buddy Variables:")
            for (var v:String in buddy.variables)
                trace("\t" + v + " --> " + buddy.variables[v])
        }
    }
Version:
  • SmartFoxServer Basic / Pro

onBuddyListError

onBuddyListError:Function
(read,write)

Called when an error occurs while loading the buddy list.

The following parameters are passed to this function.
Parameters:
error:
(String) the error message.
Example:
  • The following example shows how to handle a potential error in buddy list loading.
    smartFox.onBuddyListError = onBuddyListErrorHandler
    
    function onBuddyListErrorHandler(error:String):Void
    {
        trace("An error occurred while loading the buddy list: " + error)
    }
See also:
Version:
  • SmartFoxServer Basic / Pro

onBuddyListUpdate

onBuddyListUpdate:Function
(read,write)

Called when the status or variables of a buddy in the buddy list change.

The following parameters are passed to this function.
Parameters:
buddy:
(Object) an object representing the buddy whose status or Buddy Variables have changed. Refer to the buddyList property for a description of the buddy object's properties.
Example:
  • The following example shows how to handle the online status change of a buddy.
    smartFox.onBuddyListUpdate = onBuddyListUpdateHandler
    
    function onBuddyListUpdateHandler(buddy:Object):Void
    {
        var name:String = buddy.name
        var status:String = (buddy.isOnline) ? "online" : "offline"
    
        trace("Buddy " + name + " is currently " + status)
    }
Version:
  • SmartFoxServer Basic / Pro

onBuddyPermissionRequest

onBuddyPermissionRequest:Function
(read,write)

Called when the current user receives a request to be added to the buddy list of another user.

The following parameters are passed to this function.
Parameters:
sender :
(String) the name of the user requesting to add the current user to his/her buddy list.
message:
(String) a message accompaining the permission request. This message can't be sent from the client-side, but it's part of the advanced server-side buddy list features.
Example:
  • The following example shows how to handle the request to be added to a buddy list.
    smartFox.onBuddyPermissionRequest = onBuddyPermissionRequestHandler
    
    function onBuddyPermissionRequestHandler(sender:String, message:String):Void
    {
        // Display an alert attaching a movieclip from the Flash library
        var alert_mc:MovieClip = attachMovie("customAlertPanel", "customAlertPanel", 100)
    
        alert_mc.name_lb.text = sender
        alert_mc.message_lb.text = message
    }
See also:
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

onBuddyRoom

onBuddyRoom:Function
(read,write)

Called when a response to a getBuddyRoom request is received.

The following parameters are passed to this function.
Parameters:
idList:
(Array) the list of id of the rooms in which the buddy is currently logged; if users can't be present in more than one room at the same time, the list will contain one room id only, at 0 index.
Example:
  • The following example shows how to join the same room in which the buddy currently is.
    smartFox.onBuddyRoom = onBuddyRoomHandler
    
    var buddy:Object = smartFox.getBuddyByName("jack")
    smartFox.getBuddyRoom(buddy)
    
    function onBuddyRoomHandler(idList:Array):Void
    {
        // Reach the buddy in his room
        smartFox.join(idList[0])
    }
See also:
Version:
  • SmartFoxServer Basic / Pro

onConfigLoadFailure

onConfigLoadFailure:Function
(read,write)

Called when an error occurs while loading the external SmartFoxClient configuration file.

The following parameters are passed to this function.
Parameters:
message:
(String) the error message.
Example:
  • The following example shows how to handle a potential error in configuration loading.
    smartFox.onConfigLoadFailure = onConfigLoadFailureHandler
    
    smartFox.loadConfig("testEnvironmentConfig.xml")
    
    function onConfigLoadFailureHandler(message:String):Void
    {
        trace("Failed loading config file: " + message)
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

onConfigLoadSuccess

onConfigLoadSuccess:Function
(read,write)

Called when the external SmartFoxClient configuration file has been loaded successfully.
This handler is called only if the autoConnect parameter of the loadConfig method is set to false; otherwise the connection is made and the onConnection event fired.

No parameters are provided.
Example:
  • The following example shows how to handle a successful configuration loading.
    smartFox.onConfigLoadSuccess = onConfigLoadSuccessHandler
    
    smartFox.loadConfig("testEnvironmentConfig.xml", false)
    
    function onConfigLoadSuccessHandler():Void
    {
        trace("Config file loaded, now connecting...")
    
        smartFox.connect(smartFox.ipAddress, smartFox.port)
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

onConnection

onConnection:Function
(read,write)

Called when a response to the connect request is received.
The connection to SmartFoxServer may have succeeded or failed: the success parameter must be checked.

The following parameters are passed to this function.
Parameters:
success:
(Boolean) the connection result: true if the connection succeeded, false if the connection failed.
Example:
  • The following example shows how to handle the connection result.
        smartFox.onConnect = onConnectionHandler
    
    smartFox.connect("127.0.0.1", 9339)
    
    function onConnectionHandler(success:Boolean):Void
    {
        if (success)
            trace("Connection successful")
        else
            trace("Connection failed")
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

onConnectionLost

onConnectionLost:Function
(read,write)

Called when the connection with SmartFoxServer is closed (either from the client or from the server).

No parameters are provided.
Example:
  • The following example shows how to handle a "connection lost" event.
    smartFox.onConnectionLost = onConnectionLostHandler
    
    function onConnectionLostHandler():Void
    {
        trace("Connection lost!")
    
        // TODO: disable application interface
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

onCreateRoomError

onCreateRoomError:Function
(read,write)

Called when an error occurs during the creation of a room.
Usually this happens when a client tries to create a room but its name is already taken.

The following parameters are passed to this function.
Parameters:
error:
(String) the error message.
Example:
  • The following example shows how to handle a potential error in room creation.
    smartFox.onCreateRoomError = onCreateRoomErrorHandler
    
    var roomObj:Object = new Object()
    roomObj.name = "The Entrance"
    roomObj.maxUsers = 50
    
    smartFox.createRoom(roomObj)
    
    function onCreateRoomErrorHandler(error:String):Void
    {
        trace("Room creation error; the following error occurred: " + error)
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

onExtensionResponse

onExtensionResponse:Function
(read,write)

Called when a command/response from a server-side extension is received.

The following parameters are passed to this function.
Parameters:
dataObj:
(Object) an object containing all the data sent by the server-side extension; by convention, a String property called _cmd should always be present, to distinguish between different responses coming from the same extension.
type :
(String) one of the following response protocol types: PROTOCOL_XML, PROTOCOL_STR, PROTOCOL_JSON. By default PROTOCOL_XML is used.
Example:
  • The following example shows how to handle an extension response.
    smartFox.onExtensionResponse = onExtensionResponseHandler
    
    function onExtensionResponseHandler(dataObj:Object, type:String):Void
    {
        var command:String = dataObj._cmd
    
        // Handle XML responses
        if (type == SmartFoxClient.PROTOCOL_XML)
        {
            // TODO: check command and perform required actions
        }
    
        // Handle RAW responses
        else if (type == SmartFoxClient.PROTOCOL_STR)
        {
            // TODO: check command and perform required actions
        }
    
        // Handle JSON responses
        else if (type == SmartFoxClient.PROTOCOL_JSON)
        {
            // TODO: check command and perform required actions
        }
    }
Version:
  • SmartFoxServer Pro

onJoinRoom

onJoinRoom:Function
(read,write)

Called when a room is joined successfully.

The following parameters are passed to this function.
Parameters:
room:
(Room) the Room object representing the joined room.
Example:
  • The following example shows how to handle an successful room joining.
    smartFox.onJoinRoom = onJoinRoomHandler
    
    smartFox.joinRoom("The Entrance")
    
    function onJoinRoomHandler(room:Room):Void
    {
        trace("Room " + room.getName() + " joined successfully")
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onJoinRoomError

onJoinRoomError:Function
(read,write)

Called when an error occurs while joining a room.
This error could happen, for example, if the user is trying to join a room which is currently full.

The following parameters are passed to this function.
Parameters:
error:
(String) the error message.
Example:
  • The following example shows how to handle a potential error in room joining.
    smartFox.onJoinRoomError = onJoinRoomErrorHandler
    
    smartFox.joinRoom("The Entrance")
    
    function onJoinRoomErrorHandler(error:String):Void
    {
        trace("Room join error; the following error occurred: " + error)
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

onLogin

onLogin:Function
(read,write)

Called when the login to a SmartFoxServer zone has been attempted.

The following parameters are passed to this function.
Parameters:
response:
(Object) an object containing the login result data.
The response object contains the following properties:
success :
(Boolean) the login result: true if the login to the provided zone succeeded; false if login failed.
name :
(String) the user's actual username.
error :
(String) the error message in case of login failure.

NOTE 1: the server sends the username back to the client because not all usernames are valid: for example, those containing bad words may have been filtered during the login process.

NOTE 2: for SmartFoxServer PRO. If the Zone you are accessing uses a custom login the login-response will be sent from server side and you will need to handle it using the onExtensionResponse handler.
Additionally you will need to manually set the myUserId and myUserName properties if you need them. (This is automagically done by the API when using a default login)
Example:
  • The following example shows how to handle the login result.
    smartFox.onLogin = onLoginHandler
    
    smartFox.login("simpleChat", "jack")
    
    function onLoginHandler(response:Object):Void
    {
        if (response.success)
            trace("Successfully logged in as " + response.name)
        else
            trace("Zone login error; the following error occurred: " + response.error)
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onLogout

onLogout:Function
(read,write)

Called when the user logs out successfully.
After a successful logout the user is still connected to the server, but he/she has to login again into a zone, in order to be able to interact with the server.

No parameters are provided.
Example:
  • The following example shows how to handle the "logout" event.
    smartFox.onLogout = onLogoutHandler
    
    smartFox.logout()
    
    function onLogoutHandler():Void
    {
        trace("Logged out successfully")
    }
See also:
Since:
  • SmartFoxServer Pro v1.5.5
Version:
  • SmartFoxServer Basic / Pro

onModeratorMessage

onModeratorMessage:Function
(read,write)

Called when a message from a Moderator is received.

The following parameters are passed to this function.
Parameters:
message:
(String) the Moderator's message.
sender :
(User) the User object representing the Moderator.
Example:
  • The following example shows how to handle a message coming from a Moderator.
    smartFox.onModeratorMessage = onModeratorMessageHandler
    
    function onModeratorMessageHandler(message:String, sender:User):Void
    {
        trace("Moderator " + sender.getName() + " said: " + message)
    }
Since:
  • SmartFoxServer Pro v1.4.5
Version:
  • SmartFoxServer Basic / Pro

onObjectReceived

onObjectReceived:Function
(read,write)

Called when an Actionscript object is received.

The following parameters are passed to this function.
Parameters:
obj :
(Object) the Actionscript object received.
sender:
(User) the User object representing the user that sent the Actionscript object.
Example:
  • The following example shows how to handle an Actionscript object received from a user.
    smartFox.onObjectReceived = onObjectReceivedHandler
    
    function onObjectReceivedHandler(obj:Object, sender:User):Void
    {
        // Assuming another client sent his X and Y positions in two properties called px, py
        trace("Data received from user: " + sender.getName())
        trace("X = " + obj.px + ", Y = " + obj.py)
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onPlayerSwitched

onPlayerSwitched:Function
(read,write)

Called in response to the switchPlayer request.
The request to turn a player into a spectator may fail if another user did the same before your request, and there was only one spectator slot available.

The following parameters are passed to this function.
Parameters:
success:
(Boolean) the switch result: true if the player was turned into a player, otherwise false.
newId :
(int) the player id assigned by the server to the user. (-1 when successful)
room :
(Room) the Room object representing the room where the switch occurred.
Example:
  • The following example shows how to turn a player into a spectator.
    smartFox.onPlayerSwitched = onPlayerSwitchedHandler
    
    smartFox.switchPlayer()
    
    function onPlayerSwitchedHandler(success:Boolean, newId:Number):Void
    {
        if (success)
            trace("You have been turned into a spectator; your id is: " + newId)
        else
            trace("The attempt to switch from player to spectator failed!")
    }
Version:
  • SmartFoxServer Pro

onPrivateMessage

onPrivateMessage:Function
(read,write)

Called when a private chat message is received.

The following parameters are passed to this function.
Parameters:
message:
(String) the private message received.
sender :
(User) the User object representing the user that sent the message; this property is undefined if the sender isn't in the same room of the recipient.
userId :
(Number) the user id of the sender (useful in case of private messages across different rooms, when the sender object is not available).
roomId :
(Number) the id of the room where the sender is.
Example:
  • The following example shows how to handle a private message.
    smartFox.onPrivateMessage = onPrivateMessageHandler
    
    smartFox.sendPrivateMessage("Hallo Jack!", 22)
    
    function onPrivateMessageHandler(message:String, sender:User, roomId:Number, userId:Number):Void
    {
        trace("User " + evt.params.sender.getName() + " sent the following private message: " + evt.params.message)
    }
Version history:
  • SmartFoxServer Pro v1.5.0 - roomId and userId parameters added.
Version:
  • SmartFoxServer Lite / Basic / Pro

onPublicMessage

onPublicMessage:Function
(read,write)

Called when a public chat message is received.

The following parameters are passed to this function.
Parameters:
message:
(String) the public message received.
sender :
(User) the User object representing the user that sent the message.
roomId :
(Number) the id of the room where the sender is.
Example:
  • The following example shows how to handle a public message.
    smartFox.onPublicMessage = onPublicMessageHandler
    
    smartFox.sendPublicMessage("Hello world!")
    
    function onPublicMessageHandler(message:String, sender:User, roomId:Number):Void
    {
        trace("User " + sender.getName() + " said: " + message)
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onRandomKey

onRandomKey:Function
(read,write)

Called when a response to a getRandomKey request is received.

The following parameters are passed to this function.
Parameters:
key:
(String) a unique random key generated by the server.
Example:
  • The following example shows how to handle the key received from the server.
    smartFox.onRandomKey = onRandomKeyHandler
    
    smartFox.getRandomKey()
    
    function onRandomKeyHandler(key:String):Void
    {
        trace("Random key received from server: " + key)
    }
See also:
Version:
  • SmartFoxServer Pro

onRoomAdded

onRoomAdded:Function
(read,write)

Called when a new room is created in the zone where the user is currently logged in.

The following parameters are passed to this function.
Parameters:
room:
(Room) the Room object representing the room that was created.
Example:
  • The following example shows how to handle a new room being created in the zone.
    smartFox.onRoomAdded = onRoomAddedHandler
    
    var roomObj:Object = new Object()
    roomObj.name = "The Entrance"
    roomObj.maxUsers = 50
    
    smartFox.createRoom(roomObj)
    
    function onRoomAddedHandler(room:Room):Void
    {
        trace("Room " + room.getName() + " was created")
    
        // TODO: update available rooms list in the application interface
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onRoomDeleted

onRoomDeleted:Function
(read,write)

Called when a room is removed from the zone where the user is currently logged in.

The following parameters are passed to this function.
Parameters:
room:
(Room) the Room object representing the room that was removed.
Example:
  • The following example shows how to handle a new room being removed in the zone.
    smartFox.onRoomDeleted = onRoomDeletedHandler
    
    function onRoomDeletedHandler(room:Room):Void
    {
        trace("Room " + room.getName() + " was removed")
    
        // TODO: update available rooms list in the application interface
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

onRoomLeft

onRoomLeft:Function
(read,write)

Called when a room is left in multi-room mode, after a response to a leaveRoom request is received.

The following parameters are passed to this function.
Parameters:
roomId:
(Number) the id of the room that was left.
Example:
  • The following example shows how to handle the "room left" event.
    smartFox.onRoomLeft = onRoomLeftHandler
    
    function onRoomLeftHandler(roomId:Number):Void
    {
        trace("You left room " + roomId)
    }
See also:
Version:
  • SmartFoxServer Basic / Pro

onRoomListUpdate

onRoomListUpdate:Function
(read,write)

Called when the list of rooms available in the current zone is received.
If the default login mechanism provided by SmartFoxServer is used, then this handler is called right after a successful login.
This is because the SmartFoxServer API, internally, call the getRoomList method after a successful login is performed.
If a custom login handler is implemented, the room list must be manually requested to the server by calling the mentioned method.

The following parameters are passed to this function.
Parameters:
roomList:
(Object) an object containing all the Room objects for the zone logged in by the user.
Example:
  • The following example shows how to handle the list of rooms sent by SmartFoxServer.
    smartFox.onRoomListUpdate = onRoomListUpdateHandler
    
    smartFox.login("simpleChat", "jack")
    
    function onRoomListUpdateHandler(roomList:Object):Void
    {
        // Dump the names of the available rooms in the "simpleChat" zone
        for (var r:String in roomList)
            trace(roomList[r].getName())
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onRoomVariablesUpdate

onRoomVariablesUpdate:Function
(read,write)

Called when Room Variables are updated.
A user receives this notification only from the room(s) where he/she is currently logged in. Also, only the variables that changed are transmitted.

The following parameters are passed to this function.
Parameters:
room :
(Room) the Room object representing the room where the update took place.
changedVars:
(Array) an associative array with the names of the changed variables as keys. The array can also be iterated through numeric indexes (0 to changedVars.length) to get the names of the variables that changed.
NOTE: the changedVars array contains the names of the changed variables only, not the actual values. To retrieve them the Room.getVariable / Room.getVariables methods can be used.
Example:
  • The following example shows how to handle an update in Room Variables.
    smartFox.onRoomVariablesUpdate = onRoomVariablesUpdateHandler
    
    function onRoomVariablesUpdateHandler(room:Room, changedVars:Array):Void
    {
        // Iterate on the 'changedVars' array to check which variables were updated
        for (var v:String in changedVars)
            trace(v + " room variable was updated; new value is: " + room.getVariable(v))
    }
Version:
  • SmartFoxServer Basic / Pro

onRoundTripResponse

onRoundTripResponse:Function
(read,write)

Called when a response to the roundTripBench request is received.
The "roundtrip time" represents the number of milliseconds that it takes to a message to go from the client to the server and back to the client.
A good way to measure the network lag is to send continuos requests (every 3 or 5 seconds) and then calculate the average roundtrip time on a fixed number of responses (i.e. the last 10 measurements).

The following parameters are passed to this function.
Parameters:
elapsed:
(Number) the roundtrip time.
Example:
  • The following example shows how to check the average network lag time.
    smartFox.onRoundTripResponse = onRoundTripResponseHandler
    
    var totalPingTime:Number = 0
    var pingCount:Number = 0
    
    smartFox.roundTripBench() // TODO: this method must be called repeatedly every 3-5 seconds to have a significant average value
    
    function onRoundTripResponseHandler(elapsed:Number):Void
    {
        // We assume that it takes the same time to the ping message to go from the client to the server
        // and from the server back to the client, so we divide the elapsed time by 2.
        totalPingTime += elapsed / 2
        pingCount++
    
        var avg:Number = Math.round(totalPingTime / pingCount)
    
        trace("Average lag: " + avg + " milliseconds")
    }
See also:
Version:
  • SmartFoxServer Lite / Basic / Pro

onSpectatorSwitched

onSpectatorSwitched:Function
(read,write)

Called when a response to the switchSpectator request is received.
The request to turn a spectator into a player may fail if another user did the same before your request, and there was only one player slot available.

The following parameters are passed to this function.
Parameters:
success:
(Boolean) the switch result: true if the spectator was turned into a player, otherwise false.
newId :
(Number) the player id assigned by the server to the user.
room :
(Room) the Room object representing the room where the switch occurred.
Example:
  • The following example shows how to check the handle the spectator switch.
    smartFox.onSpectatorSwitched = onSpectatorSwitchedHandler
    
    smartFox.switchSpectator()
    
    function onSpectatorSwitchedHandler(success:Boolean, newId:Number, room:Room):Void
    {
        if (success)
            trace("You have been turned into a player; your id is " + newId)
        else
            trace("The attempt to switch from spectator to player failed")
    }
Version:
  • SmartFoxServer Basic / Pro

onUserCountChange

onUserCountChange:Function
(read,write)

Called when the number of users and/or spectators changes in a room within the current zone.
This event allows to keep track in realtime of the status of all the zone rooms in terms of users and spectators.
In case many rooms are used and the zone handles a medium to high traffic, this notification can be turned off to reduce bandwidth consumption, since a message is broadcasted to all users in the zone each time a user enters or exits a room.

The following parameters are passed to this function.
Parameters:
room:
(Room) the Room object representing the room where the change occurred.
Example:
  • The following example shows how to check the handle the spectator switch notification.
    smartFox.onUserCountChange = onUserCountChangeHandler
    
    function onUserCountChangeHandler(room:Room):Void
    {
        // Assuming this is a game room
    
        var roomName:String = room.getName()
        var playersNum:Number = room.getUserCount()
        var spectatorsNum:Number = room.getSpectatorCount()
    
        trace("Room " + roomName + "has " + playersNum + " players and " + spectatorsNum + " spectators")
    }
Version:
  • SmartFoxServer Basic / Pro

onUserEnterRoom

onUserEnterRoom:Function
(read,write)

Called when another user joins the current room.

The following parameters are passed to this function.
Parameters:
roomId:
(Number) the id of the room joined by a user (useful in case multi-room presence is allowed).
user :
(User) the User object representing the user that joined the room.
Example:
  • The following example shows how to check the handle the user entering room notification.
    smartFox.onUserEnterRoom = onUserEnterRoomHandler
    
    function onUserEnterRoomHandler(roomId:Number, user:User):Void
    {
        trace("User " + user.getName() + " entered the room")
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onUserLeaveRoom

onUserLeaveRoom:Function
(read,write)

Called when a user leaves the current room.
This handler is also called when a user gets disconnected from the server.

The following parameters are passed to this function.
Parameters:
roomId :
(Number) the id of the room left by a user (useful in case multi-room presence is allowed).
userId :
(Number) the id of the user that left the room (or got disconnected).
userName:
(String) the name of the user.
Example:
  • The following example shows how to check the handle the user leaving room notification.
    smartFox.onUserLeaveRoom = onUserLeaveRoomHandler
    
    function onUserLeaveRoomHandler(roomId:Number, userId:Number, userName:String):Void
    {
        trace("User " + userName + " left the room")
    }
Version:
  • SmartFoxServer Lite / Basic / Pro

onUserVariablesUpdate

onUserVariablesUpdate:Function
(read,write)

Called when a user in the current room updates his/her User Variables.

The following parameters are passed to this function.
Parameters:
user :
(User) the User object representing the user who updated his/her variables.
changedVars:
(Array) an associative array with the names of the changed variables as keys. The array can also be iterated through numeric indexes (0 to changedVars.length) to get the names of the variables that changed.
NOTE: the changedVars array contains the names of the changed variables only, not the actual values. To retrieve them the User.getVariable / User.getVariables methods can be used.
Example:
  • The following example shows how to handle an update in User Variables.
    smartFox.onUserVariablesUpdate = onUserVariablesUpdateHandler
    
    function onUserVariablesUpdateHandler(user:User, changedVars:Array):Void
    {
        // We assume that each user has px and py variables representing the users's avatar coordinates in a 2D environment
    
        if (changedVars["px"] != null || changedVars["py"] != null)
        {
            trace("User " + user.getName() + " moved to new coordinates:")
            trace("\t px: " + user.getVariable("px"))
            trace("\t py: " + user.getVariable("py"))
        }
    }
Version:
  • SmartFoxServer Lite / Basic / Pro