sfs2x.client
Class SmartFox

java.lang.Object
  extended by sfs2x.client.SmartFox
All Implemented Interfaces:
sfs2x.client.core.IDispatchable

public class SmartFox
extends java.lang.Object
implements sfs2x.client.core.IDispatchable

SmartFox is the main class of the SmartFoxServer 2X API. It is responsible for connecting the client to a SmartFoxServer instance and for dispatching all asynchronous events. Developers always interact with SmartFoxServer through this class.

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

Version:
1.0.0
Author:
The gotoAndPlay() Team http://www.smartfoxserver.com http://www.gotoandplay.it
See Also:
http://www.smartfoxserver.com

Constructor Summary
SmartFox()
           
SmartFox(boolean debug)
          Creates a new SmartFox instance.
 
Method Summary
 void addEventListener(java.lang.String eventType, sfs2x.client.core.IEventListener listener)
           
 void addJoinedRoom(Room room)
          *Private*
 void connect()
           
 void connect(java.lang.String host)
           
 void connect(java.lang.String host, int port)
          Establishes a connection between the client and a SmartFoxServer 2X instance.
 void disconnect()
          Closes the connection between the client and the SmartFoxServer 2X instance.
 void dispatchEvent(BaseEvent evt)
           
 void enableLagMonitor(boolean enabled)
           
 void enableLagMonitor(boolean enabled, int interval)
           
 void enableLagMonitor(boolean enabled, int interval, int queueSize)
          Enables the automatic realtime monitoring of the lag between the client and the server (round robin) When turned on, the SFSEvent.PING_PONG event type is dispatched continuously, providing the average of the last ten measured lag values.
 IBuddyManager getBuddyManager()
          Returns a reference to the Buddy Manager.
 int getCompressionThreshold()
          Returns the current compression threshold.
 ConfigData getConfig()
          Returns the client configuration details.
 java.lang.String getConnectionMode()
           
 java.lang.String getCurrentIp()
          Returns the IP address of the SmartFoxServer 2X instance to which the client is connected.
 int getCurrentPort()
          Returns the TCP port of the SmartFoxServer 2X instance to which the client is connected.
 java.lang.String getCurrentZone()
          Returns the Zone currently in use, if the user is already logged in.
 sfs2x.client.core.EventDispatcher getDispatcher()
           
 java.util.List<Room> getJoinedRooms()
          Returns a list of Room objects representing the Rooms currently joined by the client.
 sfs2x.client.util.LagMonitor getLagMonitor()
          *Private*
 Room getLastJoinedRoom()
          Returns the object representing the last Room joined by the client, if any.
 org.slf4j.Logger getLogger()
          Returns a reference to the internal Logger instance used by SmartFoxServer 2X.
 int getMaxMessageSize()
          Returns the maximum size of messages allowed by the server.
 User getMySelf()
          Returns the User object representing the client when connected to a SmartFoxServer 2X instance.
 int getReconnectionSeconds()
          *Private*
 Room getRoomById(int id)
          Retrieves a Room object from its id.
 Room getRoomByName(java.lang.String name)
          Retrieves a Room object from its name.
 java.util.List<Room> getRoomList()
          Returns a list of Room objects representing the Rooms currently "watched" by the client.
 java.util.List<Room> getRoomListFromGroup(java.lang.String groupId)
          Retrieves the list of Rooms which are part of the specified Room Group.
 IRoomManager getRoomManager()
          Returns a reference to the Room Manager.
 java.lang.String getSessionToken()
          Return the unique session token.
 sfs2x.client.bitswarm.BitSwarmClient getSocketEngine()
          *Private*
 IUserManager getUserManager()
          Returns a reference to the User Manager.
 java.lang.String getVersion()
          Returns the current version of the SmartFoxServer 2X ActionScript 3 API.
 void handleClientDisconnection(java.lang.String reason)
          *Private*
 void handleHandShake(BaseEvent evt)
           
 void handleLogin(BaseEvent evt)
           
 void handleLogout()
          *Private*
 void initUdp()
           
 void initUdp(java.lang.String udpHost)
           
 void initUdp(java.lang.String udpHost, int udpPort)
          Initializes the UDP protocol by performing an handshake with the server.
 boolean isConnected()
          Indicates whether the client is connected to the server or not.
 boolean isDebug()
          Indicates whether the client-server messages debug is enabled or not.
 boolean isJoining()
          *Private*
 boolean isUdpAvailable()
          Indicates whether the UPD protocol is available or not in the current runtime.
 boolean isUdpInited()
          Return true if the UDP handshake has been performed successfully
 void loadConfig()
           
 void loadConfig(boolean connectOnSuccess)
           
 void loadConfig(java.lang.String filePath)
           
 void loadConfig(java.lang.String filePath, boolean connectOnSuccess)
          Loads the client configuration file.
 void removeAllEventListeners()
           
 void removeEventListener(java.lang.String eventType, sfs2x.client.core.IEventListener listener)
           
 void removeJoinedRoom(Room room)
          *Private*
 void send(sfs2x.client.requests.IRequest request)
          Sends a request to the server.
 void setDebug(boolean debug)
          *Private*
 void setJoining(boolean joining)
          *Private*
 void setLastJoinedRoom(Room lastJoinedRoom)
          *Private*
 void setMySelf(User mySelf)
          *Private*
 void setReconnectionSeconds(int seconds)
          *Private*
 void setUseBlueBox(boolean useBlueBox)
           
 boolean useBlueBox()
          Indicates whether the client should attempt a tunnelled http connection through the BlueBox in case a socket connection can't be established.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SmartFox

public SmartFox(boolean debug)
Creates a new SmartFox instance.

Parameters:
debug - If true, the SmartFoxServer API debug messages are logged.

Example
The following example instantiates the SmartFox class while enabling the debug messages:

SmartFox sfs = new SmartFox(true);
See Also:
setDebug(boolean)

SmartFox

public SmartFox()
Method Detail

enableLagMonitor

public void enableLagMonitor(boolean enabled,
                             int interval,
                             int queueSize)
Enables the automatic realtime monitoring of the lag between the client and the server (round robin) When turned on, the SFSEvent.PING_PONG 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 performed successfully only.

Parameters:
enabled - The lag monitoring status: true to start the monitoring, false to stop it.
interval - An optional amount of seconds to pause between each query (recommended 3-4s)
queueSize - The amount of values stored temporarily and used to calculate the average lag
enabled - The lag monitoring status: true to start the monitoring, false to stop it.
See Also:
SFSEvent.PING_PONG

enableLagMonitor

public void enableLagMonitor(boolean enabled)

enableLagMonitor

public void enableLagMonitor(boolean enabled,
                             int interval)

getSocketEngine

public sfs2x.client.bitswarm.BitSwarmClient getSocketEngine()
*Private*


getLagMonitor

public sfs2x.client.util.LagMonitor getLagMonitor()
*Private*


isConnected

public boolean isConnected()
Indicates whether the client is connected to the server or not.

Example
The following example checks the connection status:

System.out.println("Am I connected?" + sfs.isConnected());


getVersion

public java.lang.String getVersion()
Returns the current version of the SmartFoxServer 2X ActionScript 3 API.

Example
The following example traces the SmartFoxServer API version to the console:

System.out.println("Current API version:" + sfs.getVersion());


getConfig

public ConfigData getConfig()
Returns the client configuration details. If the configuration hasn't been loaded yet, a null object is returned.

See Also:
loadConfig()

useBlueBox

public boolean useBlueBox()
Indicates whether the client should attempt a tunnelled http connection through the BlueBox in case a socket connection can't be established.

NOTE: this property must be set before the connect() method is called. Also, after a connection is established, this property does not return the current connection mode (socket or http); for this purpose use the connectionMode property.

See Also:
getConnectionMode(), loadConfig()

setUseBlueBox

public void setUseBlueBox(boolean useBlueBox)

getConnectionMode

public java.lang.String getConnectionMode()

getCompressionThreshold

public int getCompressionThreshold()
Returns the current compression threshold.

This value represents the maximum message size (in bytes) before the protocol compression is activated. It is determined by the server configuration.


getMaxMessageSize

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


getRoomById

public Room getRoomById(int id)
Retrieves a Room object from its id.

NOTE: the same object is returned by the IRoomManager.getRoomById() method, accessible through the roomManager getter; this was replicated on the SmartFox class for handy access due to its usually frequent usage.

Parameters:
id - The id of the Room.

Example
The following example retrieves a Room object and traces its name:

int roomId = 3; Room room = sfs.getRoomById(roomId); System.out.println("The name of Room " + roomId + " is " + room.getName());
Returns:
An object representing the requested Room; null if no Room object with the passed id exists in the Rooms list.
See Also:
getRoomByName(String), getRoomList(), getRoomManager()

getRoomByName

public Room getRoomByName(java.lang.String name)
Retrieves a Room object from its name.

NOTE: the same object is returned by the IRoomManager.getRoomByName() method, accessible through the roomManager getter; this was replicated on the SmartFox class for handy access due to its usually frequent usage.

Parameters:
name - The name of the Room.

Example
The following example retrieves a Room object and traces its id:

String roomName = "The Lobby"; Room room = sfs.getRoomByName(roomName); System.out.println("The ID of Room '" + roomName + "' is " + room.getId());

Returns:
An object representing the requested Room; null if no Room object with the passed name exists in the Rooms list.
See Also:
getRoomById(int), getRoomList(), getRoomManager()

getRoomListFromGroup

public java.util.List<Room> getRoomListFromGroup(java.lang.String groupId)
Retrieves the list of Rooms which are part of the specified Room Group.

NOTE: the same list is returned by the IRoomManager.getRoomListFromGroup() method, accessible through the roomManager getter; this was replicated on the SmartFox class for handy access due to its usually frequent usage.

Parameters:
groupId - The name of the Group.
Returns:
The list of Room objects belonging to the passed Group.
See Also:
getRoomManager(), Room

connect

public void connect(java.lang.String host,
                    int port)
Establishes a connection between the client and a SmartFoxServer 2X instance. If no argument is passed, the client will use the settings loaded via loadConfig() method.

The client usually connects to a SmartFoxServer instance through a socket connection. In case a socket connection can't be established, and the useBlueBox property is set to true, a tunnelled http connection through the BlueBox module is attempted. When a successful connection is established, the connectionMode property can be used to check the current connection mode.

Parameters:
host - The address of the server to connect to.
port - The TCP port to connect to.

Example
The following example connects to a local SmartFoxServer 2X instance:

sfs.connect("127.0.0.1", 9933);

Throws:
ArgumentError - If an invalid host/address or port is passed, and it can't be found in the loaded settings.
See Also:
loadConfig(), setUseBlueBox(boolean), getConnectionMode(), disconnect(), SFSEvent.CONNECTION

connect

public void connect(java.lang.String host)

connect

public void connect()

disconnect

public void disconnect()
Closes the connection between the client and the SmartFoxServer 2X instance.

See Also:
connect(String, int), SFSEvent.CONNECTION_LOST

isDebug

public boolean isDebug()
Indicates whether the client-server messages debug is enabled or not. If set to true, detailed debugging informations for all the incoming and outgoing messages are provided.

Debugging can be enabled when instantiating the SmartFox class too.


setDebug

public void setDebug(boolean debug)
*Private*


getCurrentIp

public java.lang.String getCurrentIp()
Returns the IP address of the SmartFoxServer 2X instance to which the client is connected.

See Also:
getCurrentPort(), connect(), loadConfig()

getCurrentPort

public int getCurrentPort()
Returns the TCP port of the SmartFoxServer 2X instance to which the client is connected.

See Also:
getCurrentIp(), connect(), loadConfig()

getCurrentZone

public java.lang.String getCurrentZone()
Returns the Zone currently in use, if the user is already logged in.

See Also:
loadConfig(), LoginRequest

getMySelf

public User getMySelf()
Returns the User object representing the client 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:
User.isItMe(), LoginRequest

setMySelf

public void setMySelf(User mySelf)
*Private*


getLogger

public org.slf4j.Logger getLogger()
Returns a reference to the internal Logger instance used by SmartFoxServer 2X.


getLastJoinedRoom

public Room getLastJoinedRoom()
Returns the object representing the last Room joined by the client, if any. This property is null if no Room was joined.

NOTE: setting the lastJoinedRoom property manually can disrupt the API functioning. Use the JoinRoomRequest request to join a new Room instead.

See Also:
getJoinedRooms(), JoinRoomRequest

setLastJoinedRoom

public void setLastJoinedRoom(Room lastJoinedRoom)
*Private*


getJoinedRooms

public java.util.List<Room> getJoinedRooms()
Returns a list of Room objects representing the Rooms currently joined by the client.

NOTE: the same list is returned by the IRoomManager.getJoinedRooms() method, accessible through the roomManager getter; this was replicated on the SmartFox class for handy access due to its usually frequent usage.

See Also:
getLastJoinedRoom(), getRoomManager(), Room, JoinRoomRequest

getRoomList

public java.util.List<Room> getRoomList()
Returns a list of Room 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.

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 IRoomManager.getRoomList() method, accessible through the roomManager getter; this was replicated on the SmartFox class for handy access due to its usually frequent usage.

See Also:
getRoomManager(), JoinRoomRequest, SubscribeRoomGroupRequest, UnsubscribeRoomGroupRequest

getRoomManager

public IRoomManager getRoomManager()
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 Room objects.


getUserManager

public IUserManager getUserManager()
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 User objects.


getBuddyManager

public IBuddyManager getBuddyManager()
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.


isUdpAvailable

public boolean isUdpAvailable()
Indicates whether the UPD protocol is available or not in the current runtime. UPD is available in a ActionScript 3 client if it is executed in the Adobe AIR 2.0 (or higher) runtime only.

Using the UDP protocol in an application requires that a handshake is performed between the client and the server. By default this is NOT done by the SmartFoxServer 2X API, to avoid allocating resources that might never be used. In order to activate the UDP support, the initUDP() method must be invoked explicitly.

See Also:
initUdp(String, int)

isUdpInited

public boolean isUdpInited()
Return true if the UDP handshake has been performed successfully

See Also:
initUdp(String, int)

initUdp

public void initUdp()
See Also:
initUdp(String, int)

initUdp

public void initUdp(java.lang.String udpHost)
See Also:
initUdp(String, int)

initUdp

public void initUdp(java.lang.String udpHost,
                    int udpPort)
Initializes the UDP protocol by performing an handshake with the server. In ActionScript 3, the UDP protocol is available exclusively if the client is executed in the Adobe AIR 2.0 (or higher) runtime. In order to properly activate the UDP support for the AIR runtime, an instance of the AirUDPManager class contained in the SmartFoxServer 2X ActionScript 3 API must be provided. Also, if udpHost or udpPort arguments are not passed, the client will use the settings loaded via loadConfig() method.

This method needs to be called only once. It can be executed at any moment provided that a connection to the server has already been established. After a successful initialization, UDP requests can be sent to the server-side Extension at any moment.

MTU note

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

Another interesting matter is that there is no fixed size for the MTU, because each operating system uses a slightly different value. Because of this we suggest a conservative data size of 1000-1200 bytes per packet, to avoid packet loss. The SFS2X protocol compression allows to send 2-3KBytes of uncompressed data, which usually is squeezed down to a size of ~1000 bytes. If you have a larger amount of data to send, we suggest you to organize it in smaller chunks so that they don't exceed the suggested MTU size.

More details about the MTU can be found at the page linked below.

Parameters:
udpHost - The IP address of the server to connect to.
udpPort - The UDP port to connect to.

Example
The following example initializes the UDP communication, sends a request to an Extension and handles the related events:

private void someMethod() { sfs.addEventListener(SFSEvent.UDP_INIT, new IEventListener() { public void dispatch(BaseEvent evt) throws SFSException { if ((Boolean)evt.getArguments().get("success")) { // Connection successful: execute an Extension call via UDP sfs.send( new ExtensionRequest("udpTest", new SFSObject(), null, true) ); } else { System.out.println("UDP initialization failed!"); } } }); sfs.initUdp(); }
Throws:
ArgumentError - If an invalid address or port is passed, and it can't be found in the loaded settings.
See Also:
isUdpAvailable(), loadConfig(), http://en.wikipedia.org/wiki/Maximum_transmission_unit, SFSEvent.UDP_INIT

isJoining

public boolean isJoining()
*Private*


setJoining

public void setJoining(boolean joining)
*Private*


getSessionToken

public java.lang.String getSessionToken()
Return the unique session token. The Session token is a String sent by the server to the client after the initial handshake


getDispatcher

public sfs2x.client.core.EventDispatcher getDispatcher()
Specified by:
getDispatcher in interface sfs2x.client.core.IDispatchable

getReconnectionSeconds

public int getReconnectionSeconds()
*Private*


setReconnectionSeconds

public void setReconnectionSeconds(int seconds)
*Private*


send

public void send(sfs2x.client.requests.IRequest request)
Sends a request to the server. All the available request objects can be found in the requests package.

Parameters:
request - A request object.

Example
The following example sends a login request:

sfs.send( new LoginRequest("KermitTheFrog", "KermitPass", "TheMuppetZone") );

Example
The following example sends a "join room" request.

sfs.send( new JoinRoomRequest("Lobby") );

Example
The following example creates an object containing some parameters and sends it to the server-side Extension.

private void someMethod() { ISFSObject params = new SFSObject(); params.putInt("x", 10); params.putInt("y", 37);

sfs.send( new ExtensionRequest("setPosition", params) ); }

See Also:
sfs2x.client.requests, sfs2x.client.requests.buddylist, sfs2x.client.requests.game

loadConfig

public void loadConfig(java.lang.String filePath,
                       boolean connectOnSuccess)
Loads the client configuration file.

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

The external XML configuration file has the following structure; ip, port and zone parameters are mandatory, all other parameters are optional:

<!-- SFS2X Client Configuration file --> <SmartFoxConfig> <ip>127.0.0.1</ip> <port>9933</port> <zone>SimpleChat</zone>

<debug>true</debug>

<udpIp>127.0.0.1</udpIp> <udpPort>9934</udpPort>

<httpPort>8080</httpPort> <useBlueBox>true</useBlueBox> <blueBoxPollingRate>500</blueBoxPollingRate> </SmartFoxConfig>

Parameters:
filePath - Filename of the external XML configuration, including its path relative to the folder of the application swf file.
connectOnSuccess - A flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.

Example
The following example loads an external configuration file and, on loading completion, connects to the server:

private void someMethod() { SmartFox sfs = new SmartFox();

sfs.addEventListener(SFSEvent.CONFIG_LOAD_SUCCESS, new IEventListener() { public void dispatch(BaseEvent evt) throws SFSException { // Configuration loaded successfully, now connect sfs.connect(); } }); sfs.addEventListener(SFSEvent.CONFIG_LOAD_FAILURE, new IEventListener() { public void dispatch(BaseEvent evt) throws SFSException { System.out.println("Failed loading configuration file"); } });

sfs.loadConfig("testConfig.xml", false); }

See Also:
connect(), SFSEvent.CONFIG_LOAD_SUCCESS, SFSEvent.CONFIG_LOAD_FAILURE

loadConfig

public void loadConfig(java.lang.String filePath)

loadConfig

public void loadConfig(boolean connectOnSuccess)

loadConfig

public void loadConfig()

addJoinedRoom

public void addJoinedRoom(Room room)
                   throws com.smartfoxserver.v2.exceptions.SFSException
*Private*

Throws:
com.smartfoxserver.v2.exceptions.SFSException

removeJoinedRoom

public void removeJoinedRoom(Room room)
*Private*


handleHandShake

public void handleHandShake(BaseEvent evt)

handleLogin

public void handleLogin(BaseEvent evt)

handleClientDisconnection

public void handleClientDisconnection(java.lang.String reason)
*Private*


handleLogout

public void handleLogout()
*Private*


dispatchEvent

public void dispatchEvent(BaseEvent evt)

addEventListener

public void addEventListener(java.lang.String eventType,
                             sfs2x.client.core.IEventListener listener)
Specified by:
addEventListener in interface sfs2x.client.core.IDispatchable

removeEventListener

public void removeEventListener(java.lang.String eventType,
                                sfs2x.client.core.IEventListener listener)

removeAllEventListeners

public void removeAllEventListeners()