SmartFoxClient

Kind of class:public class
Package:it.gotoandplay.smartfoxserver
Inherits from:EventDispatcher
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:48:04
SmartFoxClient is the main class in the SmartFoxServer API.
This class is responsible for connecting to the server and handling all related events.

NOTE: in the provided examples, smartFox always indicates a SmartFoxClient instance.
Events broadcasted to listeners:
  • SFSEvent with type: onAdminMessage
    • Dispatched when a message from the Administrator is received.
  • SFSEvent with type: onDebugMessage
    • Dispatched when a debug message is traced by the SmartFoxServer API.
  • SFSEvent with type: onExtensionResponse
    • Dispatched when a command/response from a server-side extension is received.
  • SFSEvent with type: onRoomDeleted
    • Dispatched when a room is removed from the zone where the user is currently logged in.
  • SFSEvent with type: onUserEnterRoom
    • Dispatched when another user joins the current room.
  • SFSEvent with type: onUserLeaveRoom
    • Dispatched when a user leaves the current room.
  • SFSEvent with type: onUserCountChange
    • Dispatched when the number of users and/or spectators changes in a room within the current zone.
  • SFSEvent with type: onConfigLoadSuccess
    • Dispatched when the external SmartFoxClient configuration file has been loaded successfully.
  • SFSEvent with type: onConfigLoadFailure
    • Dispatched when an error occurs while loading the external SmartFoxClient configuration file.
  • SFSEvent with type: onConnection
    • Dispatched in response to the connect request.
  • SFSEvent with type: onConnectionLost
    • Dispatched when the connection with SmartFoxServer is closed (either from the client or from the server).
  • SFSEvent with type: onBuddyList
    • Dispatched when the buddy list for the current user is received or a buddy is added/removed.
  • SFSEvent with type: onBuddyListError
    • Dispatched when an error occurs while loading the buddy list.
  • SFSEvent with type: onBuddyPermissionRequest
    • Dispatched when the current user receives a request to be added to the buddy list of another user.
  • SFSEvent with type: onJoinRoom
    • Dispatched when a room is joined successfully.
  • SFSEvent with type: onJoinRoomError
    • Dispatched when an error occurs while joining a room.
  • SFSEvent with type: onRoomAdded
    • Dispatched when a new room is created in the zone where the user is currently logged in.
  • SFSEvent with type: onCreateRoomError
    • Dispatched when an error occurs during the creation of a room.
  • SFSEvent with type: onBuddyRoom
  • SFSEvent with type: onRoomListUpdate
    • Dispatched when the list of rooms available in the current zone is received.
  • SFSEvent with type: onRandomKey
  • SFSEvent with type: onRoomLeft
    • Dispatched when a room is left in multi-room mode, in response to a leaveRoom request.
  • SFSEvent with type: onLogin
    • Dispatched when the login to a SmartFoxServer zone has been attempted.
  • SFSEvent with type: onLogout
    • Dispatched when the user logs out successfully.
  • SFSEvent with type: onRoundTripResponse
  • SFSEvent with type: onPublicMessage
    • Dispatched when a public chat message is received.
  • SFSEvent with type: onPrivateMessage
    • Dispatched when a private chat message is received.
  • SFSEvent with type: onModeratorMessage
    • Dispatched when a message from a Moderator is received.
  • SFSEvent with type: onObjectReceived
    • Dispatched when an Actionscript object is received.
  • SFSEvent with type: onBuddyListUpdate
    • Dispatched when the status or variables of a buddy in the buddy list change.
  • SFSEvent with type: onRoomVariablesUpdate
    • Dispatched when Room Variables are updated.
  • SFSEvent with type: onUserVariablesUpdate
    • Dispatched when a user in the current room updates his/her User Variables.
  • SFSEvent with type: onSpectatorSwitched
  • SFSEvent with type: onPlayerSwitched

Summary


Constructor
Constants
Instance properties
  • ipAddress : String
    • The SmartFoxServer IP address.
  • port : int
    • The SmartFoxServer connection port.
  • defaultZone : String
    • The default login zone.
  • 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.
  • buddyList : Array
    • An array containing the objects representing each buddy of the user's buddy list.
  • myBuddyVars : Array
    • The current user's Buddy Variables.
  • debug : Boolean
    • Toggle the client-side debugging informations.
  • myUserId : int
    • The current user's SmartFoxServer id.
  • myUserName : String
    • The current user's SmartFoxServer username.
  • playerId : int
    • 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.
  • activeRoomId : int
    • The property stores the id of the last room joined by the current user.
  • httpPort : int
    • The TCP port used by the embedded webserver.
  • rawProtocolSeparator : String
    • Get/set the character used as separator for the String (raw) protocol.
  • isConnected : Boolean
    • A boolean flag indicating if the current user is connected to the server.
  • httpPollSpeed : int
    • The minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.
  • properties : Object
Instance methods
  • loadConfig (configFile:String = "config.xml", autoConnect:Boolean = true) : void
    • Load a client configuration file.
  • getConnectionMode : String
    • Get the current connection mode.
  • connect (ipAdr:String, port:int = 9339) : void
    • Establish a connection to SmartFoxServer.
  • disconnect : void
    • Close the current connection to SmartFoxServer.
  • addBuddy (buddyName:String) : void
    • Add a user to the buddy list.
  • autoJoin : void
    • Automatically join the the default room (if existing) for the current zone.
  • clearBuddyList : void
    • Remove all users from the buddy list.
  • createRoom (roomObj:Object, roomId:int = -1) : void
    • Dynamically create a new room in the current zone.
  • getAllRooms : Array
    • Get the list of rooms in the current zone.
  • getBuddyByName (buddyName:String) : Object
    • Get a buddy from the buddy list, using the buddy's username as key.
  • getBuddyById (id:int) : 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.
  • getRoom (roomId:int) : Room
    • Get a Room object, using its id as key.
  • getRoomByName (roomName:String) : Room
    • Get a Room object, using its name as key.
  • getRoomList : void
    • Retrieve the updated list of rooms in the current zone.
  • getActiveRoom : Room
    • Get the currently active Room object.
  • getRandomKey : void
    • Retrieve a random string key from the server.
  • getUploadPath : String
    • Get the default upload path of the embedded webserver.
  • getVersion : String
    • Get the SmartFoxServer Flash API version.
  • joinRoom (newRoom:*, pword:String = "", isSpectator:Boolean = false, dontLeave:Boolean = false, oldRoom:int = -1) : void
    • Join a room.
  • leaveRoom (roomId:int) : void
    • Disconnect the user from the given room.
  • loadBuddyList : void
    • Load the buddy list for the current user.
  • login (zone:String, name:String, pass:String) : void
    • Perform the default login procedure.
  • logout : void
    • Log the user out of the current zone.
  • removeBuddy (buddyName:String) : void
    • Remove a buddy from the buddy list.
  • roundTripBench : void
    • Send a roundtrip request to the server to test the connection' speed.
  • sendBuddyPermissionResponse (allowBuddy:Boolean, targetBuddy:String) : void
    • Grant current user permission to be added to a buddy list.
  • sendPublicMessage (message:String, roomId:int = -1) : void
    • Send a public message.
  • sendPrivateMessage (message:String, recipientId:int, roomId:int = -1) : void
    • Send a private message to a user.
  • sendModeratorMessage (message:String, type:String, id:int = -1) : void
    • Send a Moderator message to the current zone, the current room or a specific user in the current room.
  • sendObject (obj:Object, roomId:int = -1) : void
    • Send an Actionscript object to the other users in the current room.
  • sendObjectToGroup (obj:Object, userList:Array, roomId:int = -1) : void
    • Send an Actionscript object to a group of users in the room.
  • sendXtMessage (xtName:String, cmd:String, paramObj:*, type:String = "xml", roomId:int = -1) : void
    • Send a request to a server side extension.
  • setBuddyBlockStatus (buddyName:String, status:Boolean) : void
    • Block or unblock a user in the buddy list.
  • setBuddyVariables (varList:Array) : void
    • Set the current user's Buddy Variables.
  • setRoomVariables (varList:Array, roomId:int = -1, setOwnership:Boolean = true) : void
    • Set one or more Room Variables.
  • setUserVariables (varObj:Object, roomId:int = -1) : void
    • Set on or more User Variables.
  • switchSpectator (roomId:int = -1) : void
    • Turn a spectator inside a game room into a player.
  • switchPlayer (roomId:int = -1) : void
    • Turn a player inside a game room into a spectator.
  • uploadFile (fileRef:FileReference, id:int = -1, nick:String = "", port:int = -1) : void
    • Upload a file to the embedded webserver.

Constructor

SmartFoxClient

public function SmartFoxClient (
debug:Boolean = false)

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

Constants

CONNECTION_MODE_DISCONNECTED

public static const CONNECTION_MODE_DISCONNECTED:String = "disconnected"
(read)

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

CONNECTION_MODE_HTTP

public static const CONNECTION_MODE_HTTP:String = "http"
(read)

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

CONNECTION_MODE_SOCKET

public static const CONNECTION_MODE_SOCKET:String = "socket"
(read)

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

MODMSG_TO_ROOM

public static const MODMSG_TO_ROOM:String = "r"
(read)

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

MODMSG_TO_USER

public static const MODMSG_TO_USER:String = "u"
(read)

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

MODMSG_TO_ZONE

public static const MODMSG_TO_ZONE:String = "z"
(read)

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

XTMSG_TYPE_JSON

public static const XTMSG_TYPE_JSON:String = "json"
(read)

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

XTMSG_TYPE_STR

public static const XTMSG_TYPE_STR:String = "str"
(read)

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

XTMSG_TYPE_XML

public static const XTMSG_TYPE_XML:String = "xml"
(read)

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

Instance properties

activeRoomId

public activeRoomId:int
(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 Basic / Pro

amIModerator

public 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

public blueBoxIpAddress:String
(read,write)

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

blueBoxPort

public blueBoxPort:Number = 0
(read,write)

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

buddyList

public 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 :
(int) 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

public 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:int
    
    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 Basic / Pro

defaultZone

public defaultZone:String
(read,write)

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

httpPollSpeed

public httpPollSpeed:int
(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

public httpPort:int = 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

public ipAddress:String
(read,write)

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

isConnected

public isConnected:Boolean
(read,write)

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.isConnected ? "connected" : "not connected"))
Version:
  • SmartFoxServer Basic / Pro

myBuddyVars

public 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

public myUserId:int
(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 Basic / Pro

myUserName

public 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 Basic / Pro

playerId

public playerId:int
(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 Basic / Pro

port

public port:int = 9339
(read,write)

The SmartFoxServer connection port.
The default port is 9339.
See also:
Version:
  • SmartFoxServer Pro

properties

public properties:Object = null
(read,write)

rawProtocolSeparator

public 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

smartConnect

public 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

Instance methods

addBuddy

public 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:
  • Before you can add or remove any buddy from the list you must load the buddy-list from the server.
    Always make sure to call {@see #loadBuddyList} before interacting with the buddy-list.

    Basic security mode
    When a buddy is added, if the buddy list is already full, the SFSEvent.onBuddyListError event is fired; otherwise the buddy list is updated and the SFSEvent.onBuddyList event is fired.
    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; the user receives the SFSEvent.onBuddyPermissionRequest event. When the permission is granted, the buddy list is updated and the SFSEvent.onBuddyList event is fired.
    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 SFSEvent.onBuddyListError event is fired.
Events broadcasted to listeners:
  • SFSEvent with type: onBuddyList
    • Dispatched when the buddy list for the current user is received or a buddy is added/removed.
  • SFSEvent with type: onBuddyListError
    • Dispatched when an error occurs while loading the buddy list.
  • SFSEvent with type: onBuddyPermissionRequest
    • Dispatched when the current user receives a request to be added to the buddy list of another user.
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

public 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.
Events broadcasted to listeners:
  • SFSEvent with type: onJoinRoom
    • Dispatched when a room is joined successfully.
  • SFSEvent with type: onJoinRoomError
    • Dispatched when an error occurs while joining a room.
Example:
  • The following example shows how to join the default room in the current zone.
    smartFox.autoJoin()
Version:
  • SmartFoxServer Basic / Pro

clearBuddyList

public 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.
Events broadcasted to listeners:
  • SFSEvent with type: onBuddyList
    • Dispatched when the buddy list for the current user is received or a buddy is added/removed.
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

public function connect (
ipAdr:String, port:int = 9339) : 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 (optional).
Events broadcasted to listeners:
  • SFSEvent with type: onConnection
    • Dispatched in response to the connect request.
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 Basic (except BlueBox connection) / Pro

createRoom

public function createRoom (
roomObj:Object, roomId:int = -1) : 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 :
(int) the maximum number of users that can join the room.
maxSpectators :
(int) 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).
joinAsSpectator:
(Boolean) if true and in case of game room, allows to join the new room as spectator (optional, default value: false).
uCount :
(Boolean) if true, the new room will receive the SFSEvent.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).
Events broadcasted to listeners:
  • SFSEvent with type: onRoomAdded
    • Dispatched when a new room is created in the zone where the user is currently logged in.
  • SFSEvent with type: onCreateRoomError
    • Dispatched when an error occurs during the creation of a room.
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 Basic / Pro

disconnect

public function disconnect (
) : void

Close the current connection to SmartFoxServer.
Events broadcasted to listeners:
  • SFSEvent with type: onConnectionLost
    • Dispatched when the connection with SmartFoxServer is closed (either from the client or from the server).
Example:
  • The following example shows how to disconnect from SmartFoxServer.
    smartFox.disconnect()
Version:
  • SmartFoxServer Basic / Pro

getActiveRoom

public 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 Basic / Pro

getAllRooms

public function getAllRooms (
) : Array

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

getBuddyById

public function getBuddyById (
id:int) : 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

public 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

public 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.
Events broadcasted to listeners:
Example:
  • The following example shows how to join the same room of a buddy.
    smartFox.addEventListener(SFSEvent.onBuddyRoom, onBuddyRoomHandler)
    
    var buddy:Object = smartFox.getBuddyByName("jack")
    smartFox.getBuddyRoom(buddy)
    
    function onBuddyRoomHandler(evt:SFSEvent):void
    {
        // Reach the buddy in his room
        smartFox.join(evt.params.idList[0])
    }
Version:
  • SmartFoxServer Basic / Pro

getConnectionMode

public function getConnectionMode (
) : String

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

getRandomKey

public 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.
Events broadcasted to listeners:
Example:
  • The following example shows how to handle the request a random key to the server.
    smartFox.addEventListener(SFSEvent.onRandomKey, onRandomKeyHandler)
    
    smartFox.getRandomKey()
    
    function onRandomKeyHandler(evt:SFSEvent):void
    {
        trace("Random key received from server: " + evt.params.key)
    }
Version:
  • SmartFoxServer Pro

getRoom

public function getRoom (
roomId:int) : Room

Get a Room object, using its id as key.
Parameters:
roomId:
the id 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 Basic / Pro

getRoomByName

public function getRoomByName (
roomName:String) : Room

Get a Room object, using its name as key.
Parameters:
roomName:
the name of the room.
Returns:
Example:
  • The following example shows how to retrieve a room from its id.
    var roomObj:Room = smartFox.getRoomByName("The Entrance")
    trace("Room id: " + roomObj.getId() + ", max users: " + roomObj.getMaxUsers())
Version:
  • SmartFoxServer Basic / Pro

getRoomList

public function getRoomList (
) : void

Retrieve the updated list of rooms in the current zone.
Unlike the getAllRooms method, 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.
Events broadcasted to listeners:
  • SFSEvent with type: onRoomListUpdate
    • Dispatched when the list of rooms available in the current zone is received.
Example:
  • The following example shows how to retrieve the room list from the server.
    smartFox.addEventListener(SFSEvent.onRoomListUpdate, onRoomListUpdateHandler)
    
    smartFox.getRoomList()
    
    function onRoomListUpdateHandler(evt:SFSEvent):void
    {
        // Dump the names of the available rooms in the current zone
        for (var r:String in evt.params.roomList)
            trace(evt.params.roomList[r].getName())
    }
Version:
  • SmartFoxServer Basic / Pro

getUploadPath

public 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

public 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 Basic / Pro

joinRoom

public function joinRoom (
newRoom:*, pword:String = "", isSpectator:Boolean = false, dontLeave:Boolean = false, oldRoom:int = -1) : void

Join a room.
Parameters:
newRoom :
the name (String) or the id (int) of the room to join.
pword :
the room's password, if it's a private room (optional).
isSpectator:
a boolean flag indicating wheter you join as a spectator or not (optional).
dontLeave :
a boolean flag indicating if the current room must be left after successfully joining the new room (optional).
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.
Events broadcasted to listeners:
  • SFSEvent with type: onJoinRoom
    • Dispatched when a room is joined successfully.
  • SFSEvent with type: onJoinRoomError
    • Dispatched when an error occurs while joining a room.
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 Basic / Pro

leaveRoom

public function leaveRoom (
roomId:int) : 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.
Events broadcasted to listeners:
  • SFSEvent with type: onRoomLeft
    • Dispatched when a room is left in multi-room mode, in response to a leaveRoom request.
Example:
  • The following example shows how to make a user leave a room.
    smartFox.leaveRoom(15)
Version:
  • SmartFoxServer Basic / Pro

loadBuddyList

public function loadBuddyList (
) : void

Load the buddy list for the current user.
Events broadcasted to listeners:
  • SFSEvent with type: onBuddyList
    • Dispatched when the buddy list for the current user is received or a buddy is added/removed.
  • SFSEvent with type: onBuddyListError
    • Dispatched when an error occurs while loading the buddy list.
Example:
  • The following example shows how to load the current user's buddy list.
    smartFox.addEventListener(SFSEvent.onBuddyList, onBuddyListHandler)
    
    smartFox.loadBuddyList()		
    
    function onBuddyListHandler(evt:SFSEvent):void
    {
        for (var b:String in smartFox.buddyList)
        {
            var buddy:Object = smartFox.buddyList[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 k:String in buddy.variables)
                trace("\t" + k + " --> " + buddy.variables[k])
        }
    }
Version:
  • SmartFoxServer Basic / Pro

loadConfig

public function loadConfig (
configFile:String = "config.xml", autoConnect:Boolean = true) : 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 SFSEvent.onConfigLoadSuccess event is dispatched.
In case of loading error, the SFSEvent.onConfigLoadFailure event id fired.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).
Parameters:
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>
        <httpPort>8080</httpPort>
        <httpPollSpeed>750</httpPollSpeed>
        <rawProtocolSeparator>%</rawProtocolSeparator>
    </SmartFoxClient>
Events broadcasted to listeners:
  • SFSEvent with type: onConfigLoadSuccess
    • Dispatched when the external SmartFoxClient configuration file has been loaded successfully.
  • SFSEvent with type: onConfigLoadFailure
    • Dispatched when an error occurs while loading the external SmartFoxClient configuration file.
Example:
  • The following example shows how to load an external configuration file.
    smartFox.addEventListener(SFSEvent.onConfigLoadSuccess, onConfigLoadSuccessHandler)
    smartFox.addEventListener(SFSEvent.onConfigLoadFailure, onConfigLoadFailureHandler)
    
    smartFox.loadConfig("testEnvironmentConfig.xml", false)
    
    function onConfigLoadSuccessHandler(evt:SFSEvent):void
    {
        trace("Config file loaded, now connecting...")
        smartFox.connect(smartFox.ipAddress, smartFox.port)
    }
    
    function onConfigLoadFailureHandler(evt:SFSEvent):void
    {
        trace("Failed loading config file: " + evt.params.message)
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

login

public 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.
Events broadcasted to listeners:
  • SFSEvent with type: onLogin
    • Dispatched when the login to a SmartFoxServer zone has been attempted.
Example:
  • The following example shows how to login into a zone.
    smartFox.addEventListener(SFSEvent.onLogin, onLoginHandler)
    
    smartFox.login("simpleChat", "jack")
    
    function onLoginHandler(evt:SFSEvent):void
    {
        if (evt.params.success)
            trace("Successfully logged in as " + evt.params.name)
        else
            trace("Zone login error; the following error occurred: " + evt.params.error)
    }
Version:
  • SmartFoxServer Basic / Pro

logout

public 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.
Events broadcasted to listeners:
  • SFSEvent with type: onLogout
    • Dispatched when the user logs out successfully.
Example:
  • The following example shows how to logout from a zone.
    smartFox.addEventListener(SFSEvent.onLogout, onLogoutHandler)
    
    smartFox.logout()
    
    function onLogoutHandler(evt:SFSEvent):void
    {
        trace("Logged out successfully")
    }
Since:
  • SmartFoxServer Pro v1.5.5
Version:
  • SmartFoxServer Basic / Pro

removeBuddy

public 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:
  • Before you can add or remove any buddy from the list you must load the buddy-list from the server.
    Always make sure to call {@see #loadBuddyList} before interacting with the buddy-list.

    Basic security mode
    When a buddy is removed, the buddy list is updated and the SFSEvent.onBuddyList event is fired.
    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.
Events broadcasted to listeners:
  • SFSEvent with type: onBuddyList
    • Dispatched when the buddy list for the current user is received or a buddy is added/removed.
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

public 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 SFSEvent.onRoundTripResponse event to be fired.
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).
Events broadcasted to listeners:
Example:
  • The following example shows how to check the average network lag time.
    smartFox.addEventListener(SFSEvent.onRoundTripResponse, onRoundTripResponseHandler)
    
    var totalPingTime:Number = 0
    var pingCount:int = 0
    
    smartFox.roundTripBench() // TODO: this method must be called repeatedly every 3-5 seconds to have a significant average value
    
    function onRoundTripResponseHandler(evt:SFSEvent):void
    {
        var time:int = evt.params.elapsed
    
        // 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 += time / 2
        pingCount++
    
        var avg:int = Math.round(totalPingTime / pingCount)
    
        trace("Average lag: " + avg + " milliseconds")
    }
Version:
  • SmartFoxServer Basic / Pro

sendBuddyPermissionResponse

public 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 SFSEvent.onBuddyPermissionRequest event is received, 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.addEventListener(SFSEvent.onBuddyPermissionRequest, onBuddyPermissionRequestHandler)
    
    var autoGrantPermission:Boolean = true
    
    function onBuddyPermissionRequestHandler(evt:SFSEvent):void
    {
        if (autoGrantPermission)
        {
            // Automatically grant permission
    
            smartFox.sendBuddyPermissionResponse(true, evt.params.sender)
        }
        else
        {
            // Display a custom alert containing grant/refuse buttons
    
            var alert_mc:CustomAlertPanel = new CustomAlertPanel()
    
            alert_mc.name_lb.text = evt.params.sender
            alert_mc.message_lb.text = evt.params.message
    
            // Display alert
            addChild(alert_mc)
        }
    }
Since:
  • SmartFoxServer Pro v1.6.0
Version:
  • SmartFoxServer Pro

sendModeratorMessage

public function sendModeratorMessage (
message:String, type:String, id:int = -1) : 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).
Events broadcasted to listeners:
  • SFSEvent with type: onModeratorMessage
    • Dispatched when a message from a Moderator is received.
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

public function sendObject (
obj:Object, roomId:int = -1) : 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).
Events broadcasted to listeners:
  • SFSEvent with type: onObjectReceived
    • Dispatched when an Actionscript object is received.
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 Basic / Pro

sendObjectToGroup

public function sendObjectToGroup (
obj:Object, userList:Array, roomId:int = -1) : 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).
Events broadcasted to listeners:
  • SFSEvent with type: onObjectReceived
    • Dispatched when an Actionscript object is received.
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 Basic / Pro

sendPrivateMessage

public function sendPrivateMessage (
message:String, recipientId:int, roomId:int = -1) : 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).
Events broadcasted to listeners:
  • SFSEvent with type: onPrivateMessage
    • Dispatched when a private chat message is received.
Example:
  • The following example shows how to send and receive a private message.
    smartFox.addEventListener(SFSEvent.onPrivateMessage, onPrivateMessageHandler)
    
    smartFox.sendPrivateMessage("Hallo Jack!", 22)
    
    function onPrivateMessageHandler(evt:SFSEvent):void
    {
        trace("User " + evt.params.sender.getName() + " sent the following private message: " + evt.params.message)
    }
Version:
  • SmartFoxServer Basic / Pro

sendPublicMessage

public function sendPublicMessage (
message:String, roomId:int = -1) : 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).
Events broadcasted to listeners:
  • SFSEvent with type: onPublicMessage
    • Dispatched when a public chat message is received.
Example:
  • The following example shows how to send and receive a public message.
    smartFox.addEventListener(SFSEvent.onPublicMessage, onPublicMessageHandler)
    
    smartFox.sendPublicMessage("Hello world!")
    
    function onPublicMessageHandler(evt:SFSEvent):void
    {
        trace("User " + evt.params.sender.getName() + " said: " + evt.params.message)
    }
Version:
  • SmartFoxServer Basic / Pro

sendXtMessage

public function sendXtMessage (
xtName:String, cmd:String, paramObj:*, type:String = "xml", roomId:int = -1) : 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).
cmd :
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). The following constants can be passed: XTMSG_TYPE_XML, XTMSG_TYPE_STR, XTMSG_TYPE_JSON.
roomId :
the id of the room where the request was originated, in case of multi-room join (optional, default value: activeRoomId).
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 = new 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.XTMSG_TYPE_JSON)
Version:
  • SmartFoxServer Pro

setBuddyBlockStatus

public 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

public function setBuddyVariables (
varList:Array) : 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 a SFSEvent.onBuddyListUpdate event is dispatched to 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.
Events broadcasted to listeners:
  • SFSEvent with type: onBuddyListUpdate
    • Dispatched when the status or variables of a buddy in the buddy list change.
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

public function setRoomVariables (
varList:Array, roomId:int = -1, setOwnership:Boolean = true) : 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).
Each Room Variable is an object containing the following properties:
name :
(String) the variable name.
val :
(*) 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).
Events broadcasted to listeners:
  • SFSEvent with type: onRoomVariablesUpdate
    • Dispatched when Room Variables are updated.
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:int = 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 SFSEvent.onRoomVariablesUpdate event is received.
    smartFox.addEventListener(SFSEvent.onRoomVariablesUpdate, onRoomVariablesUpdateHandler)
    
    function onRoomVariablesUpdateHandler(evt:SFSEvent):void
    {
        var changedVars:Array = evt.params.changedVars
    
        // 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: " + evt.params.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 property 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 Basic / Pro

setUserVariables

public function setUserVariables (
varObj:Object, roomId:int = -1) : 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).
Events broadcasted to listeners:
  • SFSEvent with type: onUserVariablesUpdate
    • Dispatched when a user in the current room updates his/her User Variables.
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 Basic / Pro

switchPlayer

public function switchPlayer (
roomId:int = -1) : 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).
Events broadcasted to listeners:
Example:
  • The following example shows how to turn a player into a spectator.
    smartFox.addEventListener(SFSEvent.onPlayerSwitched, onPlayerSwitchedHandler)
    
    smartFox.switchPlayer()
    
    function onPlayerSwitchedHandler(evt:SFSEvent):void
    {
        if (evt.params.success)
            trace("You have been turned into a spectator; your id is: " + evt.params.newId)
        else
            trace("The attempt to switch from player to spectator failed!")
    }
Version:
  • SmartFoxServer Pro

switchSpectator

public function switchSpectator (
roomId:int = -1) : 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 multi-room join (optional, default value: activeRoomId).
Events broadcasted to listeners:
Example:
  • The following example shows how to turn a spectator into a player.
    smartFox.addEventListener(SFSEvent.onSpectatorSwitched, onSpectatorSwitchedHandler)
    
    smartFox.switchSpectator()
    
    function onSpectatorSwitchedHandler(evt:SFSEvent):void
    {
        if (evt.params.success)
            trace("You have been turned into a player; your player id is " + evt.params.newId)
        else
            trace("The attempt to switch from spectator to player failed")
    }
Version:
  • SmartFoxServer Basic / Pro

uploadFile

public function uploadFile (
fileRef:FileReference, id:int = -1, nick:String = "", port:int = -1) : void

Upload a file to the embedded webserver.

NOTE: upload events fired in response should be handled by the provided FileReference object (see the example).
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).
Example:
Since:
  • SmartFoxServer Pro v1.5.0
Version:
  • SmartFoxServer Basic / Pro