SmartFox
The SmartFoxServer 2X JavaScript API main class.
Properties
Methods
new SmartFox([configObj])
Creates a new SmartFox instance.
The SmartFox class is responsible for connecting the client to a SmartFoxServer instance and for dispatching all asynchronous events.
Developers always interact with SmartFoxServer through this class.
For detailed informations please check our website: http://www.smartfoxserver.com.
The SmartFox instance can be configured through a configuration object with the following properties (all optional):
Property | Type | Description |
---|---|---|
host | string | The IP address or host name of the SmartFoxServer 2X instance to connect to. |
port | number | The WebSocket port of the SmartFoxServer 2X instance to connect to. |
useSSL | boolean | Use an encrypted SSL connection (WebSocket Secure). |
zone | string | The Zone of the SmartFoxServer 2X instance to join during the login process. |
debug | boolean | Indicates whether the client-server messages console debug should be enabled or not. |
NOTE: in the examples provided throughout the documentation, sfs
always indicates a SmartFox instance.
Example
This example instantiates the SmartFox class passing a configuration object.
function init()
{
// Create configuration object
var config = {};
config.host = "127.0.0.1";
config.port = 8080;
config.useSSL = false;
config.zone = "BasicExamples";
config.debug = false;
// Create SmartFox client instance
sfs = new SFS2X.SmartFox(config);
}
Parameter
Name | Type | Optional | Description |
---|---|---|---|
configObj |
|
Yes |
An object containing the client configuration properties. Defaults to |
- Extends
- EventDispatcher
Properties
buddyManager SFSBuddyManager
Returns a reference to the Buddy Manager.
This manager is used internally by the SmartFoxServer 2X API; the reference returned by this property gives access to the buddies list, allowing interaction with Buddy and BuddyVariable objects and access to user properties in the Buddy List system.
config object
Returns the client configuration object passed during the SmartFox instance creation.
debug boolean
Indicates whether the client-server messages console debug is enabled or not.
If set to true
, detailed debugging informations for all the incoming and outgoing messages are provided in the browser's debug console (if available).
Debugging can be enabled when instantiating the SmartFox class too by means of the configuration object.
isConnected boolean
Indicates whether the client is connected to the server or not.
Example
This example checks the connection status.
console.log("Am I connected? " + sfs.isConnected);
lastJoinedRoom SFSRoom
Returns the object representing the last Room joined by the client, if any.
This property is null
if no Room was joined.
- See also
- SmartFox#getJoinedRooms
- JoinRoomRequest
logger Logger
Returns a reference to the internal Logger instance used by SmartFoxServer 2X.
maxMessageSize number
Returns the maximum size of messages allowed by the server.
Any request exceeding this size will not be sent. The value is determined by the server configuration.
mySelf SFSUser
Returns the SFSUser object representing the client itself when connected to a SmartFoxServer 2X instance.
This object is generated upon successful login only, so it is null
if login was not performed yet.
NOTE: setting the mySelf property manually can disrupt the API functioning.
- See also
- SFSUser#isItMe
- LoginRequest
nodeId string
[CLUSTER] The identifier of the cluster node which the current SmartFox instance is connected to.
If the SmartFox instance is not connected to a cluster node, this property is null
.
roomManager SFSRoomManager
Returns a reference to the Room Manager.
This manager is used internally by the SmartFoxServer 2X API; the reference returned by this property gives access to the Rooms list and Groups, allowing interaction with SFSRoom objects.
sessionToken string
Returns the unique session token of the client.
The session token is a string sent by the server to the client after the initial handshake.
It is required as mean of identification when uploading files to the server (see specific documentation).
userManager SFSUserManager
Returns a reference to the User Manager.
This manager is used internally by the SmartFoxServer 2X API; the reference returned by this property gives access to the users list, allowing interaction with SFSUser objects.
version string
Returns the current version of the SmartFoxServer 2X JavaScript API.
Methods
addEventListener(evtType, callback, scope)
Registers an event listener function that will receive notification of an event.
If you no longer need an event listener, remove it by calling the removeEventListener() method, or memory issues could arise. In fact event listeners are not automatically removed from memory.
Example
This example shows how to add a number of common event listeners to the SmartFox instance, usually during initialization:
function init()
{
sfs = new SFS2X.SmartFox();
// Add LoggerEvent listeners
sfs.logger.addEventListener(SFS2X.LoggerEvent.DEBUG, onDebugMessage, this);
sfs.logger.addEventListener(SFS2X.LoggerEvent.INFO, onInfoMessage, this);
sfs.logger.addEventListener(SFS2X.LoggerEvent.WARNING, onWarningMessage, this);
sfs.logger.addEventListener(SFS2X.LoggerEvent.ERROR, onErrorMessage, this);
// Add SFSEvent listeners
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this);
sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this);
sfs.addEventListener(SFS2X.SFSEvent.LOGIN, onLogin, this);
sfs.addEventListener(SFS2X.SFSEvent.LOGOUT, onLogout, this);
sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this);
sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN, onRoomJoin, this);
}
Parameters
Name | Type | Optional | Description |
---|---|---|---|
evtType |
|
|
The type of event to listen to, among those available in the SFSEvent, SFSBuddyEvent and LoggerEvent classes. |
callback |
|
|
The listener function that processes the event. This function should accept an object as its only parameter, which in turn contains the event parameters. |
scope |
|
|
The object that acts as a context for the event listener: it is the object that acts as a "parent scope" for the callback function, thus providing context (i.e. access to variables and other mehtods) to the function itself. |
- Inherited from
- EventDispatcher#addEventListener
- See also
- SFSEvent
- SFSBuddyEvent
- LoggerEvent
- SmartFox#removeEventListener
connect([host][, port][, useSSL])
Establishes a connection between the client and a SmartFoxServer 2X instance.
If one or more arguments are missing, the client will use the corresponding settings passed during the SmartFox class instantiation.
Example
This example connects to a local SmartFoxServer 2X instance.
function someMethod()
{
sfs = new SFS2X.SmartFox();
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
// Connect
sfs.connect(127.0.0.1, 8080);
}
function onConnection(evtParams)
{
if (evtParams.success)
console.log("Connection established");
else
console.log("Connection failed");
}
Parameters
Name | Type | Optional | Description |
---|---|---|---|
host |
string |
Yes |
The address of the server to connect to. Defaults to |
port |
number |
Yes |
The TCP port to connect to. Defaults to |
useSSL |
boolean |
Yes |
Use an encrypted SSL connection. Defaults to |
- See also
- SmartFox#disconnect
- SFSEvent.CONNECTION
disconnect()
Closes the connection between the client and the SmartFoxServer 2X instance.
- See also
- SmartFox#connect
- SFSEvent.CONNECTION_LOST
enableLagMonitor(enabled[, interval][, queueSize])
Enables the automatic realtime monitoring of the lag between the client and the server (round robin).
When turned on, the pingPong event type is dispatched continuously, providing the average of the last ten measured lag values. The lag monitoring is automatically halted when the user logs out of a Zone or gets disconnected.
NOTE: the lag monitoring can be enabled after the login has been completed successfully only.
Parameters
Name | Type | Optional | Description |
---|---|---|---|
enabled |
boolean |
|
The lag monitoring status: |
interval |
number |
Yes |
The amount of seconds to wait between each query (recommended 3-4s). Defaults to |
queueSize |
number |
Yes |
The amount of values stored temporarily and used to calculate the average lag. Defaults to |
- See also
- SFSEvent.PING_PONG
getJoinedRooms() → Array of SFSRoom
Returns a list of SFSRoom objects representing the Rooms currently joined by the client.
NOTE: the same list is returned by the SFSRoomManager.getJoinedRooms() method, accessible through the roomManager property; this was replicated on the SmartFox class for handy access due to its usually frequent usage.
- See also
- SmartFox#lastJoinedRoom
- SmartFox#roomManager
- SFSRoom
- JoinRoomRequest
- Returns
-
Array of SFSRoom
The list of SFSRoom objects representing the Rooms joined by the client.
getRoomById(id) → SFSRoom
Retrieves a SFSRoom object from its id.
NOTE: the same object is returned by the SFSRoomManager.getRoomById() method, accessible through the roomManager property; this was replicated on the SmartFox class for handy access due to its usually frequent usage.
Example
This example retrieves a SFSRoom object and traces its name.
var roomId = 3;
var room = sfs.getRoomById(roomId);
console.log("The name of Room " + roomId + " is " + room.name);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
id |
number |
|
The id of the Room. |
- See also
- SmartFox#getRoomByName
- SFSRoomManager#getRoomById
- SFSRoom
- Returns
-
SFSRoom
The object representing the requested Room;undefined
if no SFSRoom object with the passed id exists in the Rooms list.
getRoomByName(name) → SFSRoom
Retrieves a SFSRoom object from its name.
NOTE: the same object is returned by the SFSRoomManager.getRoomByName() method, accessible through the roomManager property; this was replicated on the SmartFox class for handy access due to its usually frequent usage.
Example
This example retrieves a SFSRoom object and traces its id.
var roomName = "The Lobby";
var room = sfs.getRoomByName(roomName);
console.log("The ID of Room '" + roomName + "' is " + room.id);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
name |
string |
|
The name of the Room. |
- See also
- SmartFox#getRoomById
- SFSRoomManager#getRoomByName
- SFSRoom
- Returns
-
SFSRoom
The object representing the requested Room;undefined
if no SFSRoom object with the passed name exists in the Rooms list.
getRoomList() → Array of SFSRoom
Returns the list of SFSRoom objects representing the Rooms currently "watched" by the client.
The list contains all the Rooms that are currently joined and all the Rooms belonging to the Room Groups that have been subscribed by the client.
NOTE 1: at login time, the client automatically subscribes all the Room Groups specified in the Zone's Default Room Groups setting.
NOTE 2: the same list is returned by the SFSRoomManager.getRoomList() method, accessible through the roomManager property; this was replicated on the SmartFox class for handy access due to its usually frequent usage.
- See also
- SmartFox#roomManager
- JoinRoomRequest
- SubscribeRoomGroupRequest
- UnsubscribeRoomGroupRequest
- Returns
-
Array of SFSRoom
The list of SFSRoom objects representing the Rooms available on the client.
getRoomListFromGroup(groupId) → Array of SFSRoom
Retrieves the list of Rooms which are part of the specified Room Group.
NOTE: the same list is returned by the SFSRoomManager.getRoomListFromGroup() method, accessible through the roomManager property; this was replicated on the SmartFox class for handy access due to its usually frequent usage.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
groupId |
string |
|
The name of the Group. |
- See also
- SFSRoomManager#getRoomListFromGroup
- SFSRoom
- Returns
-
Array of SFSRoom
The list of SFSRoom objects belonging to the passed Group.
killConnection()
Simulates an abrupt disconnection from the server.
This method should be used for testing and simulations only, otherwise use the
removeEventListener(evtType, callback)
Removes an event listener.
Parameters
Name | Type | Optional | Description |
---|---|---|---|
evtType |
|
|
The type of event to remove, among those available in the SFSevent, SFSBuddyEvent and LoggerEvent classes. |
callback |
|
|
The listener function to be removed. |
- Inherited from
- EventDispatcher#removeEventListener
- See also
- SFSEvent
- SFSBuddyEvent
- SmartFox#addEventListener
send(request)
Sends a request to the server.
Examples
This example shows how to send a login request.
sfs.send(new SFS2X.LoginRequest("KermitTheFrog", "kermitPwd", null, "TheMuppetZone"));
This example sends a "join room" request.
sfs.send(new SFS2X.JoinRoomRequest("Lobby"));
This example creates an object containing some parameters and sends it to the server-side Extension.
var params = new SFS2X.SFSObject();
params.putInt("x", 10);
params.putInt("y", 37);
sfs.send(new SFS2X.ExtensionRequest("setPosition", params));
Parameter
Name | Type | Optional | Description |
---|---|---|---|
request |
|
A request object. |
setClientDetails(platformId, version)
Allows to specify custom client details that will be used to gather statistics about the client platform via the AdminTool's Analytics Module.
By default no details are sent and the client type is the generic "JavaScript".
NOTE: this method must be called before the connection is started. The length of the two strings combined must be less than 512 characters.
Parameters
Name | Type | Optional | Description |
---|---|---|---|
platformId |
string |
|
An identification string for the client, like the browser name for example. |
version |
string |
|
An additional string to describe the client version, like the browser version for example. |