SmartFoxClient

EventDispatcher
SmartFoxClient

Description

This is the class responsible for connecting to the server and handling all related events.  For all the SmartFoxServer events fired by this class please refer to the SFSEvent class.

The SmartFoxClient class also fires the following Flash/Flex events

  • IOErrorEvent: fired in case a network I/O error occurs
  • SecurityErrorEvent: fired if the Flash Player sandbox security is violated

Version

1.4.0

Status

Final

Author

The gotoAndPlay() Team

Copyright

© 2006-2007 gotoAndPlay()

http://www.gotoandplay.it

http://www.smartfoxserver.com

Summary
This is the class responsible for connecting to the server and handling all related events.
An array containing the objects representing each buddy of the client’s buddy list.
Toggles the client-side debugging informations.
A number representing the current userId.
A string representing the name we’re currently using in the server.
A number representing the id of the client as a player.
A boolean flag indicating if the user is recognized as moderator.
The property stores the id of the last room the user has entered.
The TCP port used by the embedded webserver.
Get/set the character used as a separator for the Raw/String protocol.
A boolean flag indicating if you are connected to the server.
The default contructor.
Add a new buddy to the buddy list.
Automatically join the the default room (if exist) for the current Zone.
Remove all contacts from the buddy list.
Dynamically create a new room in the current Zone.
Establish a connection to SmartFoxServer.
Closes the current connection to SmartFoxServer.
Get the list of rooms.
Request the roomId(s) of the room(s) a buddy is currently joined to.
Get a Room object from its id.
Get a Room object from its name.
Retrieve the list of rooms in the current Zone.
Get the currently active Room object.
Gets a random string key from the server.
Get the default upload path of the embedded webserver.
Get the SmartFoxServer Flash API version.
Join a room.
Disconnect the user from the specified room.
Loads the buddy list for the current user.
Perform the default login procedure.
Log the user out of the current Zone.
Remove a buddy from the buddy list.
Send a roundTrip request to the server to test the speed of the connection.
Send a public message.
Send a private message to a user.
Send a moderator message to an entire Zone, a Room or a single User.
Send an Actionscript object to the other users in the room.
Send a request to a server side extension.
Send an Actionscript object to a group of users in the room.
Set one or more Buddy Variables.
Set on or more Room Variables.
Set on or more User Variables.
Turn a spectator inside a game room into a player.
Upload a file to the embedded webserver.

Variables

buddyList

public var buddyList: Array

An array containing the objects representing each buddy of the client’s buddy list.

Each entry in the list is an object with the following properties

  • id:int - the user id.
  • name:String - the buddy name.
  • isOnline:Boolean - true if the buddy is currently online.
  • variables:Object - with extra properties of the buddy.

Example

for (var i:String in smartFox.buddyList)
{
var name:String = smartFox.buddyList[i].name
var stat:String = smartFox.buddyList[i].isOnline ? "online" : "offline"

trace("Buddy name: " + name + " is " + stat)

// Trace all buddy variables
for (var j:String in buddyList[i].variables)
trace("Property: " + j + " => " + buddyList[i].variables[j]
}

See also

<onBuddyList>, <onBuddyListUpdate>

debug

public var debug: Boolean

Toggles the client-side debugging informations.  When turned on you will be able to inspect all server messages that are sent and received by the client in the Flash authoring environment, allowing to better debug your application and the server side interaction.

Example

var runningLocally:Boolean = true

var ip:String
var port:int = 9399
var zone:String = "myZone"

if (runningLocally)
{
smartFox.debug = true
ip = "127.0.0.1"
}
else
{
smartFox.debug = false
ip = "100.101.102.103"
}

...

myUserId

public var myUserId: int

A number representing the current userId.  The id is assigned by the server each time a client connects successfully to it.

The variable is available only after a successfull login.

Example

trace("My user ID is: " + smartFox.myUserId)

See also

login

myUserName

public var myUserName: String

A string representing the name we’re currently using in the server.

The variable is available only after a successful login.

Example

trace("I logged in as: " + smartFox.myUserName)

See also

login

playerId

public var playerId: int

A number representing the id of the client as a player.  Available only after the client joined a game room.  Once a client joins a game room he’s automatically assigned a player slot or id, based on the player slots available in the room at the moment in which the user entered.

  • In a game room for 2 players the first user who joins becomes player 1 (playerId = 1) and the second user who joins becomes player two (player = 2).
  • In a game room for 4 player where only player 3 is missing the next client who will join will be player 3 (playerId = 3).
  • If the user logged in the game room as a “spectator” his playerId will be always set to -1.

The variable is available only after a successfull login in a game room.

Example

trace("I am player " + smartFox.playerId)

See also

login

amIModerator

public var amIModerator: Boolean

A boolean flag indicating if the user is recognized as moderator.

Example

if (smartfox.amIModerator)
trace("You've moderator superpowers!")
else
trace("Sorry you're not a moderator")

activeRoomId

public var activeRoomId: int

The property stores the id of the last room the user has entered.

In most multiuser applications users can join one room at a time: in this case the property value represents the id of the current room.  If you’re allowing the clients join more than one room at the same time you will have to track the various id(s) in an array (for example) and this property should be ignored.

Example

var room:Room = smartFox.getRoom(smartFox.activeRoomId)
trace("CurrentRoom is: " + room.getName())

See also

getActiveRoom

httpPort

public var httpPort: int

The TCP port used by the embedded webserver.  By default it is set to 8080.  If the webserver is listening on another port number this property should be set to that value.

Example

trace("httpPort is: " + smartfox.httpPort)

See also

uploadFile

Properties

rawProtocolSeparator

public function get rawProtocolSeparator():String

Get/set the character used as a separator for the Raw/String protocol.  Default is %.

Example

smartFox.rawProtocolSeparator = "|"

Since

SmartFoxServer Pro v1.5.5

isConnected

public function get isConnected():Boolean

A boolean flag indicating if you are connected to the server.

Example

trace("My connection status: " + (smartFox.isConnected ? "connected" : "not connected"))

Functions

SmartFoxClient

public function SmartFoxClient(debug: Boolean = false)

The default contructor.

Parameters

debugtrue to turn on the debug messages.

Example

var smartFox:SmartFoxClient = new SmartFoxClient()

addBuddy

public function addBuddy(buddyName: String):void

Add a new buddy to the buddy list.

If the buddyList is full an SFSEvent.onBuddyListError event will be received from the server.

Parameters

buddyNamethe name of the buddy.

Return

Nothing.  Causes the SFSEvent.onBuddyList or SFSEvent.onBuddyListError events to be fired in response.

Example

smartFox.addBuddy("Lapo")

See also

buddyList, removeBuddy, loadBuddyList, clearBuddyList, SFSEvent.onBuddyList, SFSEvent.onBuddyListError

autoJoin

public function autoJoin():void

Automatically join the the default room (if exist) for the current Zone.  You can specify a default room in the config.xml file by adding the autoJoin=”true” attribute to a room (<Room></Room>) of your choice.  When a room is marked as autoJoin it becomes the default room where all clients are joined when this method is called.

Parameters

None.

Return

Nothing.  Causes the SFSEvent.onJoinRoom or SFSEvent.onJoinRoomError events to be fired in response.

Example

smartFox.autoJoin()

See also

SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

clearBuddyList

public function clearBuddyList():void

Remove all contacts from the buddy list.

Parameters

None.

Return

Nothing.  Causes the SFSEvent.onBuddyList event to be fired in response.

Example

smartFox.clearBuddyList()

See also

buddyList, <addBubby>, removeBuddy, loadBuddyList, SFSEvent.onBuddyList

createRoom

public function createRoom(roomObj: Object,  
roomId: int = -1):void

Dynamically create a new room in the current Zone.

The roomObj parameter is an object containing the following properties

  • name:String - the room name.
  • password:String - a password for the room (optional).
  • maxUsers:int - the maximum number of users that can join the room.
  • maxSpectators:int - the maximum number of spectator slots (only for game rooms).
  • isGame:Boolean - true if the room is a game room.
  • exitCurrentRoom:Boolean - a flag that can be used when creating a new game room.  By default when a new game rooms is launched, its creator is auto-joined inside the room leaving the one he was in before; if you don’t want to leave the old room you should set this property to false.
  • uCount:Boolean - a flag indicating if the new room will receive the uCount update messages.  The uCount messages are updates about the number of users in each room of the zone; if you’re not handling them in the current room it is recommended to turn it off.
  • vars:Array - an array of room variables (see below).
  • extension:Object - specifies which extension should be dynamically attached to the room (optional, see below).

A Room can be initialized with any number of Room Variables; the vars parameter in roomObj is an array of objects with the following properties

  • name:String - the variable name.
  • val:* - the variable value.
  • priv:Boolean - true if the variable is private.
  • persistent:String - true if the variable is persistent.

The extension must be a Room-level extension; the extension parameter in roomObj is an object with the following properties

  • name:String - the name used to reference the extension.
  • script:String - the file name of the extension script (for Actionscript and Python); if you use Java, you should provide the fully qualified name of the extension.  The file name is relative to the root of the extension folder (sfsExtensions/ for AS, javaExtensions/ for java).

Parameters

roomObjthe room parameters object described above.
roomIdan optional parameter only needed for advanced tasks, when using multiple room at the same time.

Return

Nothing.  Causes the SFSEvent.onRoomAdded or SFSEvent.onCreateRoomError events to be fired in response.

Example

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)

See also

SFSEvent.onRoomAdded, SFSEvent.onCreateRoomError

connect

public function connect(ipAdr: String,  
port: int = 9339):void

Establish a connection to SmartFoxServer.

Parameters

ipAdrthe ip address of the SmartFoxServer instance.
portthe TCP port of the SmartFoxServer instance (default is 9339).

Return

Nothing.  Causes the SFSEvent.onConnection event to be fired in response.

Example

smartFox.connect("127.0.0.1", 9339)

See also

disconnect, SFSEvent.onConnection, SFSEvent.onConnectionLost

disconnect

public function disconnect():void

Closes the current connection to SmartFoxServer.

Parameters

None.

Return

Nothing.  Causes the SFSEvent.onConnectionLost event to be fired in response.

Example

smartFox.disconnect()

See also

connect, SFSEvent.onConnectionLost

getAllRooms

public function getAllRooms():Array

Get the list of rooms.  This method retrieves the list of Room objects already stored on the client, so no request is sent to the server.

Parameters

None.

Return

Arraythe list of rooms available in the current Zone.

Example

smartFox.getAllRooms()

See also

getRoomList

getBuddyRoom

public function getBuddyRoom(buddy: Object):void

Request the roomId(s) of the room(s) a buddy is currently joined to.

Parameters

buddya buddy object taken from the buddyList array.

Return

Nothing.  Causes the SFSEvent.onBuddyRoom event to be fired in response.

Example

var firstBuddy:Object = smartFox.buddyList[0]
smartFox.getBuddyRoom(firstBuddy)

See also

SFSEvent.onBuddyRoom

getRoom

public function getRoom(rid: int):Room

Get a Room object from its id.

Parameters

ridthe id of the room.

Return

Roomthe Room object.

Example

var roomObj:Room = smartFox.getRoom(15)
trace("Room name: " + roomObj.getName() + ", max users: " + roomObj.getMaxUsers())

See also

getRoomByName, getRoomList

getRoomByName

public function getRoomByName(roomName: String):Room

Get a Room object from its name.

Parameters

roomNamethe name of the room.

Return

Roomthe Room object.

Example

var roomObj:Room = smartFox.getRoomByName("The Entrance")
trace("Room id: " + roomObj.getId())

See also

getRoom, getRoomList

getRoomList

public function getRoomList():void

Retrieve the list of rooms in the current Zone.

The server will send the complete list of rooms with all their properties and server side variables (Room Variables).

Parameters

None.

Return

Nothing.  Causes the SFSEvent.onRoomListUpdate event to be fired in response.

Example

smartFox.getRoomList()

See also

getRoom, getRoomByName, getAllRooms, SFSEvent.onRoomListUpdate

getActiveRoom

public function getActiveRoom():Room

Get the currently active Room object.

Please notice that SmartFoxServer allows users to be logged in two or more rooms at the same time.  If your multiuser application makes use of this feature, this API method becomes useless and you should track the room id(s) of your clients manually, for example by keeping them in an array.

Parameters

None.

Return

Roomthe currently active room.  If you’re joining your users in more than one room, the method will return the last joined room.

Example

var room:Room = smartFox.getActiveRoom()

See also

activeRoomId

getRandomKey

public function getRandomKey():void

Gets a random string key from the server.

This key is also referred in this 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.

For more details please check the Secure Login Tutorial (http://www.smartfoxserver.com- /docs- /docPages- /tutorials_pro- /09_secureLogin- /).

Parameters

None.

Return

Nothing.  Causes the SFSEvent.onRandomKey event to be fired in response.

Example

var room:Room = smartFox.getActiveRoom()

See also

SFSEvent.onRandomKey

getUploadPath

public function getUploadPath():String

Get the default upload path of the embedded webserver.

Parameters

None.

Return

Stringthe http address of the default folder in which files are uploaded.

Example

var path:String = smartFox.getUploadPath()

getVersion

public function getVersion():String

Get the SmartFoxServer Flash API version.

Parameters

None.

Return

Stringthe current version of the client API.

Example

trace("Current API version: " + smartFox.getVersion())

joinRoom

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

Join a room.

Parameters

newRoomthe id (int) or name (String) of the room to join.
pwordthe password for the room (in case it’s private).
isSpectatora boolean indicating wheter you want to join as a spectator or not (optional, default = false).
dontLeavea boolean that indicates if you want to leave the current room, after the join is successful (optional, default = false).
oldRoomthe id of the room that you want to leave (optional).

Please notice that the last two optional paramaters enable the developer to use the advanced multi-room feature of SmartFoxServer, which allows a user to be logged in two or more rooms at the same time.  If you don’t need this feature just use the first arguments.

Return

Nothing.  Causes the SFSEvent.onJoinRoom or SFSEvent.onJoinRoomError events to be fired in response.

Examples

The user requests to join a room with id = 10; by default SmartFoxServer will disconnect him from the previous room.

smartFox.joinRoom(10)

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")

The user requests to join the room with id = 15 and passes the dontLeave flag as true; this will join the user in the new room while keeping him in the old room as well.

smartFox.joinRoom(15, "", false, true)

See also

SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

leaveRoom

public function leaveRoom(roomId: int):void

Disconnect the user from the specified room.

This method should be used only when you allow users to be present in more than one room at the same time.

Parameters

roomIdthe id of the room to leave.

Return

Nothing.  Causes the SFSEvent.onRoomLeft event to be fired in response.

Example

smartFox.leaveRoom(6)

See also

SFSEvent.onRoomLeft

loadBuddyList

public function loadBuddyList():void

Loads the buddy list for the current user.  This method works only if the buddyList feature is enabled for the current zone.

Parameters

None.

Return

Nothing.  Causes the SFSEvent.onBuddyList or SFSEvent.onBuddyListError events to be fired in response.

Example

smartFox.loadBuddyList()

See also

buddyList, addBuddy, removeBuddy, clearBuddyList, SFSEvent.onBuddyList, SFSEvent.onBuddyListError

login

public function login(zone: String,
name: String,
pass: String):void

Perform the default login procedure.

Causes the SFSEvent.onLogin event to be fired in response.

The standard SmartFoxServer login method accepts guest users.  If a user logs in with an empty nickname the server automatically creates a name for the client using this format: “guest_n” where n is a progressive number.

If you need to implement your own login procedure, for example to check usernames against a database, you can add it to your code BEFORE the SmartFox login code.  This way, once the client is validated, you can just use the stadard login procedure.

Also the provided name and password are checked against the moderator list (configured in the config.xml file on the server side) and if a user matches it, he is set as a moderator.

Please also notice that duplicate names in the same zone are not allowed.

Parameters

zonethe Zone name in which you want to login.
namethe user name.
passthe user password.

Return

Nothing.  Causes an SFSEvent.onLogin event to be fired in response.

Example

smartFox.login("testZone", "Jim")

See also

logout, SFSEvent.onLogin

logout

public function logout():void

Log the user out of the current Zone.

After the logout, the user is still connected to the server but he has to login again in a Zone, in order to interact with the server.

Parameters

None.

Return

Nothing.  Causes an SFSEvent.onLogout event to be fired in response.

Example

smartFox.logout()

// The server will send us an event after the logout is performed
smartFox.addEventListener(SFSEvent.onLogout, onLogout)

public function onLogout(evt:SFSEvent):void
{
trace("I was logged out successfully")
}

Since

SmartFoxServer Pro v1.5.5

See also

login, SFSEvent.onLogout

removeBuddy

public function removeBuddy(buddyName: String):void

Remove a buddy from the buddy list.

Parameters

buddyNamethe name of the buddy to remove.

Return

Nothing.  Causes an SFSEvent.onBuddyList event to be fired in response.

Example

var buddyName:String = "Lapo"
smartFox.removeBuddy(buddyName)

See also

buddyList, addBuddy, loadBuddyList, clearBuddyList, SFSEvent.onBuddyList, SFSEvent.onBuddyListError

roundTripBench

public function roundTripBench():void

Send a roundTrip request to the server to test the speed of the connection.

The roundTrip request sends a small packet to the server which immediately responds with another small packets, firing the onRoundTripResponse event.  The time taken from the packet to travel back and forth is returned and it indicates the average network “lag” of the client.

A good way to measure the network lag is to send continuos requests (say every 3 to 5 seconds) and then calculating the average value on a fixed number of responses (i.e. the last 10 results).

Parameters

None.

Return

Nothing.  Causes an SFSEvent.onRoundTripResponse event to be fired in response.

Example

smartFox.roundTripBench()

See also

SFSEvent.onRoundTripResponse

sendPublicMessage

public function sendPublicMessage(message: String,  
roomId: int = -1):void

Send a public message.  The message is broadcasted to all users in the room.

Parameters

messagethe text of the public message.
roomIdthe id of the target room (optional, default is the currently active room).

Return

Nothing.  Causes an SFSEvent.onPublicMessage event to be fired in response.

Example

smartFox.sendPublicMessage("Hello! This is my first public message!")

See also

sendPrivateMessage, SFSEvent.onPublicMessage

sendPrivateMessage

public function sendPrivateMessage(message: String,  
recipientId: int,  
roomId: int = -1):void

Send a private message to a user.

Parameters

messagethe text of the private message.
recipientIdthe id of the recipient user.
roomIdthe id of the room from where the message was sent (optional); this is needed if you are allowing users to join multiple rooms.

Return

Nothing.  Causes an SFSEvent.onPrivateMessage event to be fired in response.

Example

smartFox.sendPrivateMessage("Hi there!", 22)

See also

sendPublicMessage, SFSEvent.onPrivateMessage

sendModeratorMessage

public function sendModeratorMessage(message: String,  
type: String,  
id: int = -1):void

Send a moderator message to an entire Zone, a Room or a single User.

In order to send these messages, the client must have moderator privileges.

Parameters

messagethe text of the message.
typethe type of message.  You can use the following constants: SmartFoxClient.MODMSG_TO_USER, SmartFoxClient.MODMSG_TO_ROOM, SmartFoxClient.MODMSG_TO_ZONE to send the message to a user, a room or to the entire Zone respectively.
idthe id of the room where the message was originated (optional).

Return

Nothing.  Causes an SFSEvent.onModeratorMessage event to be fired.

Example

smartFox.sendModeratorMessage("Greetings from the moderator", SmartFoxClient.MODMSG_TO_ROOM, smartFox.getActiveRoom())

See also

SFSEvent.onModeratorMessage

sendObject

public function sendObject(obj: Object,  
roomId: int = -1):void

Send an Actionscript object to the other users in the room.

This method can be used to send complex/nested data structures to clients, like a game move or a game status change.  Supported datatypes are: Strings, Booleans, Numbers, Arrays, Objects.

Parameters

objthe object to be sent.
roomIdthe id of the target room (optional, default is the currently active room).  You may want to use this extra parameters if you’re sending the object in a room that is different from the one you’re currently in.

Return

Nothing.  Causes an SFSEvent.onObjectReceived event to be fired.

Examples

A simple object with primitive data is sent to the other clients.

move:Object = {}
move.x = 150
move.y = 250
move.speed = 8

smartFox.sendObject(move)

An object with two arrays of items is being sent to the other clients.

itemsFound:Object = {}
itemsFound.jewels = ["necklace", "ring"]
itemsFound.weapons = ["sword", "sledgehammer"]

smartFox.sendObject(itemsFound)

See also

sendObjectToGroup, SFSEvent.onObjectReceived

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.  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.

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 messaging where reducing the amount of data is the highest priority.

Parameters

xtNamethe name of the extension.
cmdthe name of the action/command to execute in the extension.
paramObjan object containing the data to be passed to the extension.
typethe type of protocol used for serialization.  Use one of the following constants: SmartFoxClient.XTMSG_TYPE_XML, SmartFoxClient.XTMSG_TYPE_STR, SmartFoxClient.XTMSG_TYPE_JSON.
roomIdthe id of the room where the request was originated (optional).

Return

Nothing.  Can cause an SFSEvent.onExtensionResponse event to be fired in response (depending on the extension implementation).

Example

// A bullet is being fired
// Let's notify the server side extension

var request:Object = {}
request.type = "bullet"
request.posx = 100
request.posy = 200
request.speed = 10
request.angle = 45

// Invoke "fire" command on the extension called "gameExt"
smartFox.sendXtMessage("gameExt", "fire", request)

You can learn more about Server side extensions by checking section 6 of the SmartFoxServer PRO documentation.

See also

SFSEvent.onExtensionResponse

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

objthe object to be sent.
userListthe list of recipients: an Array of user id(s).
roomIdthe id of the target room (optional, default is the currently active room).  You may want to use this extra parameters if you’re sending the object in a room that is different from the one you’re currently in.

Return

Nothing.  Causes an SFSEvent.onObjectReceived event to be fired.

Example

A simple object with primitive data is sent to two users.

move:Object = {}
move.x = 150
move.y = 250
move.speed = 8

smartFox.sendObjectToGroup(move, [1, 2])

See also

sendObject, SFSEvent.onObjectReceived

setBuddyVariables

public function setBuddyVariables(varList: Array):void

Set one or more Buddy Variables.

Set a number of properties of a buddy.  These variables will be received by the other users who have added this user as a buddy.

It can be used to store additional information for a buddy like the name of his/her avatar or his current status (“Available”, “Busy”, etc).

Parameters

varListan associative array, where the key is the name of the variable and the value is the variable value.  Buddy Variables should all be strings.  If you need to use other data types you should apply the appropriate type casts.

Return

Nothing.  Causes an SFSEvent.onBuddyListUpdate event to be fired.

Example

We set two Buddy Variables to show the other buddies our status and the current audio track we’re listening to.

var bVars:Object = new Object()
bVars["status"] = "Be right back"
bVars["track"] = "What is hip"

smartFox.setBuddyVariables(bVars)

Buddy Variables are broadcasted to all other clients that added our profile to their buddy list.

See also

SFSEvent.onBuddyListUpdate

setRoomVariables

public function setRoomVariables(varList: Array,  
roomId: int = -1,
setOwnership: Boolean = true):void

Set on or more Room Variables.

Stores data on the server side.  When you set one or more Room Variables, all the other users in the room will be notified.  It is a useful feature to share data across the clients, keeping it in a centralized place on the server.

You must provide a list of objects representing each variables with the following properties.

  • name:String - the variable name.
  • val:* - the variable value; allowed datatypes are: Numbers, Strings, Booleans.
  • priv:Boolean - true to make the variable private (can be modified by its creator only); default is false.
  • persistent:Boolean - true to make the variable persistent (will exist until the creator is connected in the Zone); default is false.

If a Room Variable is set to null, it will be deleted from the server.

Parameters

varLista list of objects as described above.
roomIdthe id of the room where the variables should be set (optional).
setOwnershipfalse to prevent the room variable change ownership (default is true).

Return

Nothing.  Causes an SFSEvent.onRoomVariablesUpdate event to be fired in response.

Examples

Save a persistent “score” Room Variable.  This variable will not be destroyed when the user that created it leaves the room.

var rVars:Array = []
rVars.push( {name:"score", val:2500, persistent:true} )

smartFox.setRoomVariables(rVars)

Save two Room Variables at once.  The one called “bestTime” is private and no other user except its owner will be able to modify it.

var rVars:Array = []
rVars.push( {name:"bestTime", val:100, priv:true} )
rVars.push( {name:"bestLap", val:120} )

smartFox.setRoomVariables(rVars)

Delete a variable called “bestTime”.  To delete a room variable just set it to null.

var rVars:Array = []
rVars.push( {name:"bestTime", val:null} )

smartFox.setRoomVariables(rVars)

To save bandwidth arrays and objects are not supported.  Nevertheless we can simulate, for example, an array of values by using an index in front of the name of the variable.  This way you can send an array-like set of data without consuming too much bandwidth.

var rVars: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)

Here’s how you can handle this data when users receive the onRoomVariablesUpdate event:

smartFox.addEventListener(SFSEvent.onRoomVariablesUpdate, onRoomVariablesUpdate)

public function onRoomVariablesUpdate(evt:SFSEvent):void
{
var changedRoomVars:Array = evt.params.changedVars

for (var i:int = 0; i < changedRoomVars.length; i++)
trace("name " + i + ": " + changedRoomVars["name" + i])
}

This last example shows how to update Room Variables without affecting the variable ownership.  By default, when a user updates a server variable, he becomes the “owner” of that variable.  In some cases you may need to disable this behavoir by setting the setOwnership to false.

For example, a variable that is defined in the config.xml will be owned by the Server; if it’s not set to private its owner will change as soon as a client updates it.  To avoid this change of ownership set the flag to false.

var rVars:Array = []
rVars.push( {name:"shipPosX", val:100} )
rVars.push( {name:"shipPosY", val:200} )

smartFox.setRoomVariables(rVars, smartFox.getActiveRoom(), false)

See also

SFSEvent.onRoomVariablesUpdate

setUserVariables

public function setUserVariables(varObj: Object,  
roomId: int = -1):void

Set on or more User Variables.

Stores data on the server side.  When you set/update/delete one or more User Variable, all the other users in the room will be notified.  User Variables are a useful tool to store user profile data that to be shared with other users.

If a User Variable is set to null, it will be deleted from the server.  Also, User Variables are destroyed when the user logs out or gets disconnected.

Parameters

varObjan object where each property is one of the variables to set/update; allowed datatypes are: Numbers, Strings, Booleans.
roomIdthe room id where the request was originated (optional).

Return

Nothing.  Causes an SFSEvent.onUserVariablesUpdate event to be fired.

Example

In an avatar chat you could save the user profile (avatar name and position) in the following way.

var uVars:Object = new Object()
uVars.myAvatar = "Homer"
uVars.posx = 100
uVars.posy = 200

smartFox.setUserVariables(uVars)

User Variables are broadcasted to all the other users in the same room.

See also

SFSEvent.onUserVariablesUpdate

switchSpectator

public function switchSpectator(roomId: int = -1):void

Turn a spectator inside a game room into a player.  This operation is successful only if at least one player slot is available in the room.

Parameters

roomIdthe id of the room where the spectator should be switched (optional, default is the currently active room).  This extra parameter is useful if you’re keeping the user logged in more than one room at the same time.

Return

Nothing.  Causes an SFSEvent.onSpectatorSwitched event to be fired in response.

Example

smartFox.switchSpectator()

See also

SFSEvent.onSpectatorSwitched

uploadFile

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

Upload a file to the embedded webserver.

Parameters

fileRefthe FileReference object (see the example).
idthe user id; you only need to pass this value if you use a custom login system (optional).
nickthe user name; you only need to pass this value if you use a custom login system (optional).
portthe http server TCP port; you need to pass this value if your server is not running on the default port 8080 (optional).

Return

Nothing.  Upload events fired in response should be handled by the provided FileReference object (see the example).

Example

Check the Upload Tutorial available ad this address: http://local.smartfoxserver.com- /docs- /docPages- /tutorials_pro- /14_imageManager- /

public var buddyList: Array
An array containing the objects representing each buddy of the client’s buddy list.
public var debug: Boolean
Toggles the client-side debugging informations.
public var myUserId: int
A number representing the current userId.
public var myUserName: String
A string representing the name we’re currently using in the server.
public var playerId: int
A number representing the id of the client as a player.
public var amIModerator: Boolean
A boolean flag indicating if the user is recognized as moderator.
public var activeRoomId: int
The property stores the id of the last room the user has entered.
public var httpPort: int
The TCP port used by the embedded webserver.
public function get rawProtocolSeparator():String
Get/set the character used as a separator for the Raw/String protocol.
public function get isConnected():Boolean
A boolean flag indicating if you are connected to the server.
public function SmartFoxClient(debug: Boolean = false)
The default contructor.
public function addBuddy(buddyName: String):void
Add a new buddy to the buddy list.
public function autoJoin():void
Automatically join the the default room (if exist) for the current Zone.
public function clearBuddyList():void
Remove all contacts from the buddy list.
public function createRoom(roomObj: Object,  
roomId: int = -1):void
Dynamically create a new room in the current Zone.
public function connect(ipAdr: String,  
port: int = 9339):void
Establish a connection to SmartFoxServer.
public function disconnect():void
Closes the current connection to SmartFoxServer.
public function getAllRooms():Array
Get the list of rooms.
public function getBuddyRoom(buddy: Object):void
Request the roomId(s) of the room(s) a buddy is currently joined to.
public function getRoom(rid: int):Room
Get a Room object from its id.
The Room class is used internally by the SmartFoxClient object to store the properties of each room.
public function getRoomByName(roomName: String):Room
Get a Room object from its name.
public function getRoomList():void
Retrieve the list of rooms in the current Zone.
public function getActiveRoom():Room
Get the currently active Room object.
public function getRandomKey():void
Gets a random string key from the server.
public function getUploadPath():String
Get the default upload path of the embedded webserver.
public function getVersion():String
Get the SmartFoxServer Flash API version.
public function joinRoom(newRoom: *,  
pword: String = "",
isSpectator: Boolean = false,
dontLeave: Boolean = false,
oldRoom: int = -1):void
Join a room.
public function leaveRoom(roomId: int):void
Disconnect the user from the specified room.
public function loadBuddyList():void
Loads the buddy list for the current user.
public function login(zone: String,
name: String,
pass: String):void
Perform the default login procedure.
public function logout():void
Log the user out of the current Zone.
public function removeBuddy(buddyName: String):void
Remove a buddy from the buddy list.
public function roundTripBench():void
Send a roundTrip request to the server to test the speed of the connection.
public function sendPublicMessage(message: String,  
roomId: int = -1):void
Send a public message.
public function sendPrivateMessage(message: String,  
recipientId: int,  
roomId: int = -1):void
Send a private message to a user.
public function sendModeratorMessage(message: String,  
type: String,  
id: int = -1):void
Send a moderator message to an entire Zone, a Room or a single User.
public function sendObject(obj: Object,  
roomId: int = -1):void
Send an Actionscript object to the other users in the room.
public function sendXtMessage(xtName: String,  
cmd: String,  
paramObj: *,  
type: String = "xml",
roomId: int = -1):void
Send a request to a server side extension.
public function sendObjectToGroup(obj: Object,  
userList: Array,  
roomId: int = -1):void
Send an Actionscript object to a group of users in the room.
public function setBuddyVariables(varList: Array):void
Set one or more Buddy Variables.
public function setRoomVariables(varList: Array,  
roomId: int = -1,
setOwnership: Boolean = true):void
Set on or more Room Variables.
public function setUserVariables(varObj: Object,  
roomId: int = -1):void
Set on or more User Variables.
public function switchSpectator(roomId: int = -1):void
Turn a spectator inside a game room into a player.
public function uploadFile(fileRef: FileReference,  
id: int = -1,
nick: String = "",
port: int = -1):void
Upload a file to the embedded webserver.
Each event dispatched by the SmartFoxClient class is a SFSEvent object (it.gotoandplay.smartfoxserver.SFSEvent) which extends the flash.events.Event class.
Dispatched when an error occurs while loading the buddy list.
Dispatched when the buddy list is received.
Dispatched when a room is joined successfully.
Dispatched when an error occurs while joining a room.
Dispatched when a new room is created.
Dispatched when an error occurs during the creation of a room.
Dispatched when the connection to SmartFoxServer succeeded or failed.
Dispatched when the connection with SmartFoxServer is lost.
Dispatched in response to a SmartFoxClient.getBuddyRoom request.
Dispatched when the list of rooms available in the Zone is received.
Dispatched when a response to the SmartFoxClient.getRandomKey request is received.
Dispatched when a room is left in multi-room mode, in response of a SmartFoxClient.leaveRoom request.
Dispatched after the login to SmartFoxServer has been attempted.
Dispatched after the user logged out successfully.
Dispatched when a response to the SmartFoxClient.roundTripBench request is received.
Dispatched when a public message is received.
Dispatched when a private message is received.
Dispatched when a message from a Moderator is received.
Dispatched when an Actionscript object is received.
Dispatched when a response from a server-side extension is received.
Dispatched when the status of a buddy in the buddy list changes.
Dispatched when room variables are updated in a certain room.
Dispatched when a user updates his/her User Variables.
Dispatched when a response to the SmartFoxClient.switchSpectator request is received.