it.gotoandplay.smartfoxclient
Class SmartFoxClient

java.lang.Object
  extended by it.gotoandplay.smartfoxclient.SFSEventDispatcher
      extended by it.gotoandplay.smartfoxclient.SmartFoxClient
All Implemented Interfaces:
ISFSEventListener, it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler

public class SmartFoxClient
extends SFSEventDispatcher
implements it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler, ISFSEventListener

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.

Version:
1.5.8
Author:
The gotoAndPlay() Team
http://www.smartfoxserver.com
http://www.gotoandplay.it
See Also:
SFSEvent.onAdminMessage, SFSEvent.onDebugMessage, SFSEvent.onExtensionResponse, SFSEvent.onRoomDeleted, SFSEvent.onUserEnterRoom, SFSEvent.onUserLeaveRoom, SFSEvent.onUserCountChange

Field Summary
 int activeRoomId
          The property stores the id of the last room joined by the current user.
 boolean amIModerator
          A boolean flag indicating if the user is recognized as Moderator.
 java.lang.String blueBoxIpAddress
          The BlueBox IP address.
 int blueBoxPort
          The BlueBox connection port.
 java.util.List<Buddy> buddyList
          A List containing Buddy objects representing each buddy of the user's buddy list.
 boolean changingRoom
           
static java.lang.String CONNECTION_MODE_DISCONNECTED
          Connection mode: "disconnected".
static java.lang.String CONNECTION_MODE_HTTP
          Connection mode: "http".
static java.lang.String CONNECTION_MODE_SOCKET
          Connection mode: "socket".
 java.lang.String defaultZone
          The default login zone.
 int httpPort
          The TCP port used by the embedded webserver.
 java.lang.String ipAddress
          The SmartFoxServer IP address.
static java.lang.String MODMSG_TO_ROOM
          Moderator message type: "to room".
static java.lang.String MODMSG_TO_USER
          Moderator message type: "to user".
static java.lang.String MODMSG_TO_ZONE
          Moderator message type: "to zone".
 java.util.Map<java.lang.String,java.lang.String> myBuddyVars
          The current user's Buddy Variables.
 int myUserId
          The current user's SmartFoxServer id.
 java.lang.String myUserName
          The current user's SmartFoxServer username.
 int playerId
          The current user's id as a player in a game room.
 int port
          The SmartFoxServer connection port.
 boolean smartConnect
          A boolean flag indicating if the BlueBox http connection should be used in case a socket connection is not available.
static java.lang.String XTMSG_TYPE_JSON
          Server-side extension request/response protocol: JSON.
static java.lang.String XTMSG_TYPE_STR
          Server-side extension request/response protocol: String (aka "raw protocol").
static java.lang.String XTMSG_TYPE_XML
          Server-side extension request/response protocol: XML.
 
Constructor Summary
SmartFoxClient(boolean debug)
          The SmartFoxClient contructor.
 
Method Summary
 void __logout()
           
 void addBuddy(java.lang.String buddyName)
          Add a user to the buddy list.
 void autoJoin()
          Automatically join the the default room (if existing) for the current zone.
 void clearBuddyList()
          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.
 void clearRoomList()
           
 void connect(java.lang.String ipAdr)
          Establish a connection to SmartFoxServer using the default port 9339.
 void connect(java.lang.String ipAdr, int port)
          Establish a connection to SmartFoxServer.
 void createRoom(java.lang.String name, int maxUsers, java.util.Map<java.lang.String,java.lang.Object> roomProperties)
          Dynamically create a new room in the current zone.
 void createRoom(java.lang.String name, int maxUsers, java.util.Map<java.lang.String,java.lang.Object> roomProperties, int roomId)
          Dynamically create a new room in the current zone.
 void disconnect()
          Close the current connection to SmartFoxServer.
 Room getActiveRoom()
          Get the currently active Room object.
 java.util.Map<java.lang.Integer,Room> getAllRooms()
          Get the list of rooms in the current zone.
 long getBenchStartTime()
           
 Buddy getBuddyById(int id)
          Get a buddy from the buddy list, using the user id as key.
 Buddy getBuddyByName(java.lang.String buddyName)
          Get a buddy from the buddy list, using the buddy's username as key.
 void getBuddyRoom(Buddy buddy)
          Request the room id(s) of the room(s) where a buddy is currently located into.
 java.lang.String getConnectionMode()
          Get the current connection mode.
 int getHttpPollSpeed()
          Returns the minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.
 java.util.logging.Logger getLogger()
          Returns the Logger used to log the SmatFoxCLient debug messages.
 void getRandomKey()
          Retrieve a random string key from the server.
 char getRawProtocolSeparator()
          Returns the character used as separator for the String (raw) protocol.
 Room getRoom(int roomId)
          Get a Room object, using its id as key.
 Room getRoomByName(java.lang.String roomName)
          Get a Room object, using its name as key.
 void getRoomList()
          Retrieve the updated list of rooms in the current zone.
 java.lang.String getUploadPath()
          Get the default upload path of the embedded webserver.
 java.lang.String getVersion()
          Get the SmartFoxServer Flash API version.
 void handleEvent(SFSEvent event)
          Handles SmartFoxServer event.
 boolean isConnected()
          Returns true if the current user is connected to the server, false if the current user is not connected to the server.
 boolean isDebug()
          Return true if the debug messages are enabled, otherwise returns false.
 void joinRoom(int newRoom)
          Join a room.
 void joinRoom(int newRoom, java.lang.String pword, boolean dontLeave)
          Join a room.
 void joinRoom(int newRoom, java.lang.String pword, boolean isSpectator, boolean dontLeave)
          Join a room.
 void joinRoom(int newRoom, java.lang.String pword, boolean isSpectator, boolean dontLeave, int oldRoom)
          Join a room.
 void joinRoom(java.lang.String newRoom, java.lang.String pword, boolean dontLeave)
          Join a room.
 void joinRoom(java.lang.String newRoom, java.lang.String pword, boolean isSpectator, boolean dontLeave)
          Join a room.
 void joinRoom(java.lang.String newRoom, java.lang.String pword, boolean isSpectator, boolean dontLeave, int oldRoom)
          Join a room.
 void leaveRoom(int roomId)
          Disconnect the user from the given room.
 void loadBuddyList()
          Load the buddy list for the current user.
 void loadConfig(java.lang.String configFileName)
          Load a client configuration file.
 void loadConfig(java.lang.String configFileName, boolean autoConnect)
          Load a client configuration file.
 void loadConfig(java.net.URL configFileUrl)
          Load a client configuration file.
 void loadConfig(java.net.URL configFileUrl, boolean autoConnect)
          Load a client configuration file.
 void login(java.lang.String zone, java.lang.String name, java.lang.String pass)
          Perform the default login procedure.
 void logout()
          Log the user out of the current zone.
 void onClose()
           
 void onConnect(boolean success)
           
 void onData(java.lang.String message)
           
 void onError(java.lang.Exception e)
           
 void removeBuddy(java.lang.String buddyName)
          Remove a buddy from the buddy list.
 void roundTripBench()
          Send a roundtrip request to the server to test the connection' speed.
 void sendBuddyPermissionResponse(boolean allowBuddy, java.lang.String targetBuddy)
          Grant current user permission to be added to a buddy list.
 void sendJson(java.lang.String jsMessage)
           
 void sendModeratorMessage(java.lang.String message, java.lang.String type, int id)
          Send a Moderator message to the current zone, the current room or a specific user in the current room.
 void sendObject(SFSObject obj)
          Send an object to the other users in the current room.
 void sendObject(SFSObject obj, int roomId)
          Send an object to the other users in the current room.
 void sendObjectToGroup(SFSObject obj, int[] userList)
          Send an Actionscript object to a group of users in the room.
 void sendObjectToGroup(SFSObject obj, int[] userList, int roomId)
          Send an Actionscript object to a group of users in the room.
 void sendPrivateMessage(java.lang.String message, int recipientId)
          Send a private message to a user.
 void sendPrivateMessage(java.lang.String message, int recipientId, int roomId)
          Send a private message to a user.
 void sendPublicMessage(java.lang.String message)
          Send a public message.
 void sendPublicMessage(java.lang.String message, int roomId)
          Send a public message.
 void sendString(java.lang.String strMessage)
           
 void sendXtMessage(java.lang.String xtName, java.lang.String cmd, org.json.JSONObject paramObj)
          Send a request to a server side extension using JSON protocol.
 void sendXtMessage(java.lang.String xtName, java.lang.String cmd, org.json.JSONObject paramObj, int roomId)
          Send a request to a server side extension using JSON protocol.
 void sendXtMessage(java.lang.String xtName, java.lang.String cmd, SFSObject paramObj)
          Send a request to a server side extension using XML protocol.
 void sendXtMessage(java.lang.String xtName, java.lang.String cmd, SFSObject paramObj, int roomId)
          Send a request to a server side extension using XML protocol.
 void sendXtMessage(java.lang.String xtName, java.lang.String cmd, java.lang.String[] params)
          Send a request to a server side extension using String protocol.
 void sendXtMessage(java.lang.String xtName, java.lang.String cmd, java.lang.String[] params, int roomId)
          Send a request to a server side extension using String protocol.
 void setBuddyBlockStatus(java.lang.String buddyName, boolean status)
          Block or unblock a user in the buddy list.
 void setBuddyVariables(java.util.Map<java.lang.String,java.lang.String> varList)
          Set the current user's Buddy Variables.
 void setConnected(boolean connected)
          Sets the connected flag.
 void setDebug(boolean debug)
          Toggle the client-side debugging informations.
 void setHttpPollSpeed(int pollSpeed)
          Sets the minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.
 void setRawProtocolSeparator(char value)
          Sete the character used as separator for the String (raw) protocol.
 void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars)
          Set one or more Room Variables.
 void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars, int roomId)
          Set one or more Room Variables.
 void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars, int roomId, boolean setOwnership)
          Set one or more Room Variables.
 void setUserVariables(java.util.Map<java.lang.String,SFSVariable> vars)
          Set on or more User Variables.
 void setUserVariables(java.util.Map<java.lang.String,SFSVariable> vars, int roomId)
          Set on or more User Variables.
 void switchPlayer()
          Turn a player inside a game room into a spectator.
 void switchPlayer(int roomId)
          Turn a player inside a game room into a spectator.
 void switchSpectator()
          Turn a spectator inside a game room into a player.
 void switchSpectator(int roomId)
          Turn a spectator inside a game room into a player.
 
Methods inherited from class it.gotoandplay.smartfoxclient.SFSEventDispatcher
addEventListener, dispatchEvent, removeEventListener
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MODMSG_TO_USER

public static final java.lang.String MODMSG_TO_USER
Moderator message type: "to user".

The Moderator message is sent to a single user.

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendModeratorMessage(java.lang.String, java.lang.String, int), Constant Field Values

MODMSG_TO_ROOM

public static final java.lang.String MODMSG_TO_ROOM
Moderator message type: "to room".

The Moderator message is sent to all the users in a room.

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendModeratorMessage(java.lang.String, java.lang.String, int), Constant Field Values

MODMSG_TO_ZONE

public static final java.lang.String MODMSG_TO_ZONE
Moderator message type: "to zone".

The Moderator message is sent to all the users in a zone.

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendModeratorMessage(java.lang.String, java.lang.String, int), Constant Field Values

XTMSG_TYPE_XML

public static final java.lang.String XTMSG_TYPE_XML
Server-side extension request/response protocol: XML.

Since:
SmartFoxServer Pro v1.x.x
See Also:
SFSEvent.onExtensionResponse, Constant Field Values

XTMSG_TYPE_STR

public static final java.lang.String XTMSG_TYPE_STR
Server-side extension request/response protocol: String (aka "raw protocol").

Since:
SmartFoxServer Pro v1.x.x
See Also:
SFSEvent.onExtensionResponse, Constant Field Values

XTMSG_TYPE_JSON

public static final java.lang.String XTMSG_TYPE_JSON
Server-side extension request/response protocol: JSON.

Since:
SmartFoxServer Pro v1.x.x
See Also:
SFSEvent.onExtensionResponse, Constant Field Values

CONNECTION_MODE_DISCONNECTED

public static final java.lang.String CONNECTION_MODE_DISCONNECTED
Connection mode: "disconnected".

The client is currently disconnected from SmartFoxServer.

Since:
SmartFoxServer Pro v1.6.0
See Also:
getConnectionMode(), Constant Field Values

CONNECTION_MODE_SOCKET

public static final java.lang.String CONNECTION_MODE_SOCKET
Connection mode: "socket".

The client is currently connected to SmartFoxServer via socket.

Since:
SmartFoxServer Pro v1.6.0
See Also:
getConnectionMode(), Constant Field Values

CONNECTION_MODE_HTTP

public static final java.lang.String CONNECTION_MODE_HTTP
Connection mode: "http".

The client is currently connected to SmartFoxServer via http.

Since:
SmartFoxServer Pro v1.6.0
See Also:
getConnectionMode(), Constant Field Values

ipAddress

public volatile java.lang.String ipAddress
The SmartFoxServer IP address.

Since:
SmartFoxServer Pro v1.x.x
See Also:
connect(java.lang.String)

port

public volatile int port
The SmartFoxServer connection port. The default port is 9339.

Since:
SmartFoxServer Pro v1.x.x
See Also:
connect(java.lang.String)

defaultZone

public volatile java.lang.String defaultZone
The default login zone.

Since:
SmartFoxServer Pro v1.x.x
See Also:
loadConfig(java.lang.String)

blueBoxIpAddress

public volatile java.lang.String blueBoxIpAddress
The BlueBox IP address.

Since:
SmartFoxServer Pro v1.6.0
See Also:
smartConnect, loadConfig(java.lang.String)

blueBoxPort

public volatile int blueBoxPort
The BlueBox connection port.

Since:
SmartFoxServer Pro v1.6.0
See Also:
smartConnect, loadConfig(java.lang.String)

smartConnect

public volatile boolean smartConnect
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.

Since:
SmartFoxServer Pro v1.6.0
See Also:
loadConfig(java.lang.String)

buddyList

public volatile java.util.List<Buddy> buddyList
A List containing Buddy objects representing each buddy of the user's buddy list.

Specific buddy can be retrieved by means of the getBuddyById(int) and getBuddyByName(java.lang.String) 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.

The following example shows how to retrieve the properties of each buddy in the buddy list.

 for(Buddy buddy : smartFox.buddyList)
 {
 
     // Trace buddy properties
     System.out.println("Buddy id: " + buddy.getId());
     System.out.println("Buddy name: " + buddy.getName());
     System.out.println("Is buddy online? " + (buddy.isOnline() ? "Yes" : "No"));
     System.out.println("Is buddy blocked? " + (buddy.isBlocked() ? "Yes" : "No"));
 
     // Trace all Buddy Variables
     for(String key : buddy.getVariables().keySet())
     {
         System.out.println("\t" + key + " --> " + buddy.getVariables().get(key));
     }
 }
 

Since:
SmartFoxServer Basic (except block status) / Pro v1.x.x
See Also:
Buddy, myBuddyVars, loadBuddyList(), getBuddyById(int), getBuddyByName(java.lang.String), removeBuddy(java.lang.String), setBuddyBlockStatus(java.lang.String, boolean), setBuddyVariables(java.util.Map), SFSEvent.onBuddyList, SFSEvent.onBuddyListUpdate

myBuddyVars

public volatile java.util.Map<java.lang.String,java.lang.String> myBuddyVars
The current user's Buddy Variables.

This is a Map containing the current user's properties when he/she is present in the buddy lists of other users. See the setBuddyVariables(java.util.Map) method for more details.

The following example shows how to read the current user's own Buddy Variables.

 for(String key : smartFox.myBuddyVars.keySet())
 {
     System.out.println("Variable" + key + " --> " + smartFox.myBuddyVars.get(key));
 }
 

Since:
SmartFoxServer Pro v1.6.0
See Also:
setBuddyVariables(java.util.Map), getBuddyById(int), getBuddyByName(java.lang.String), SFSEvent.onBuddyList, SFSEvent.onBuddyListUpdate

myUserId

public volatile int myUserId
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!

The following example shows how to retrieve the user's own SmartFoxServer id.

 System.out.println("My user ID is: " + smartFox.myUserId);
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
myUserName

myUserName

public volatile java.lang.String myUserName
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!

The following example shows how to retrieve the user's own SmartFoxServer username.

 System.out.println("I logged in as: " + smartFox.myUserName);
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
myUserId, login(java.lang.String, java.lang.String, java.lang.String)

playerId

public volatile int playerId
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:

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.

The following example shows how to retrieve the user's own player id.

 System.out.println("I'm player " + smartFox.playerId);
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
Room.getMyPlayerIndex(), Room.isGame()

amIModerator

public volatile boolean amIModerator
A boolean flag indicating if the user is recognized as Moderator.

The following example shows how to check if the current user is a Moderator in the current SmartFoxServer zone.

 if(smartfox.amIModerator)
     System.out.println("I'm a Moderator in this zone");
 else
     System.out.println("I'm a standard user");
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendModeratorMessage(java.lang.String, java.lang.String, int)

activeRoomId

public volatile int activeRoomId
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) and this property should be ignored.

The following example shows how to retrieve the current room object (as an alternative to the getActiveRoom() method).

 Room room = smartFox.getRoom(smartFox.activeRoomId);
 System.out.println("Current room is: " + room.getName());
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
getActiveRoom()

changingRoom

public volatile boolean changingRoom

httpPort

public volatile int httpPort
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.

The following example shows how to retrieve the webserver's current http port.

 System.out.println("HTTP port is: " + smartfox.httpPort);
 

Since:
SmartFoxServer Pro v1.5.0
Constructor Detail

SmartFoxClient

public SmartFoxClient(boolean debug)
The SmartFoxClient contructor.

Parameters:
debug - turn on the debug messages.
Method Detail

getRawProtocolSeparator

public char getRawProtocolSeparator()
Returns the character used as separator for the String (raw) protocol.

Returns:
The character used as separator for the String (raw) protocol.
Since:
SmartFoxServer Pro v1.5.5
See Also:
XTMSG_TYPE_STR, setRawProtocolSeparator(char), sendXtMessage(java.lang.String, java.lang.String, it.gotoandplay.smartfoxclient.data.SFSObject)

setRawProtocolSeparator

public void setRawProtocolSeparator(char value)
Sete 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.

The following example shows how to set the raw protocol separator.

 smartFox.setRawProtocolSeparator('|');
 

Parameters:
value - the character used as separator for the String (raw) protocol.
Since:
SmartFoxServer Pro v1.5.5
See Also:
XTMSG_TYPE_STR, sendXtMessage(java.lang.String, java.lang.String, it.gotoandplay.smartfoxclient.data.SFSObject)

isConnected

public boolean isConnected()
Returns true if the current user is connected to the server, false if the current user is not connected to the server.

The following example shows how to check the connection status.

 System.out.println("My connection status: " + (smartFox.isConnected() ? "connected" : "not connected"));
 

Returns:
true if the current user is connected to the server, false if the current user is not connected to the server.
Since:
SmartFoxServer Basic / Pro v1.x.x

setConnected

public void setConnected(boolean connected)
Sets the connected flag.

Parameters:
connected - true if the current user is connected to the server, false if the current user is not connected to the server.
Since:
SmartFoxServer Basic / Pro v1.x.x

getHttpPollSpeed

public int getHttpPollSpeed()
Returns the minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.

Returns:
The minimum interval between two polling requests when connecting to SmartFoxServer via BlueBox module.
Since:
SmartFoxServer Pro v1.6.0
See Also:
smartConnect

setHttpPollSpeed

public void setHttpPollSpeed(int pollSpeed)
Sets 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).

The following example shows how to set the polling speed.

 smartFox.setHttpPollSpeed(200);
 

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.

Parameters:
pollSpeed - The minimum interval between two polling requests
Since:
SmartFoxServer Pro v1.6.0
See Also:
smartConnect

isDebug

public boolean isDebug()
Return true if the debug messages are enabled, otherwise returns false.

Returns:
true if the debug messages are enabled, otherwise false.

setDebug

public void setDebug(boolean debug)
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 log output. This allows a better debugging of the interaction with the server during application developement.

The following example shows how to turn on SmartFoxServer API debugging.

 SmartFoxClient smartFox = new SmartFoxClient(false);
 if(runningLocally)
 {
     smartFox.setDebug(true);
     ip = "127.0.0.1";
     port = 9339;
 }
 else
 {
     ip = "100.101.102.103";
     port = 9333;
 }
 smartFox.connect(ip, port);
 

See Also:
SFSEvent.onDebugMessage

getLogger

public java.util.logging.Logger getLogger()
Returns the Logger used to log the SmatFoxCLient debug messages.

Returns:
the Logger used to log the SmatFoxCLient debug messages.
See Also:
setDebug(boolean)

loadConfig

public void loadConfig(java.lang.String configFileName)
Load a client configuration file.

The SmartFoxClient instance can be configured through an external xml configuration file loaded at run-time. On loading completion the connect(java.lang.String) method is automatically called by the API. In case of loading error, the SFSEvent.onConfigLoadFailure event is fired.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).

NOTE: The external xml configuration file has the following structure: ip 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>
 

The following example shows how to load an external configuration file.

 smartFox.addEventListener(SFSEvent.onConfigLoadFailure, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Failed loading config file: " +
             evt.getParams().getString("message"));
       }
   });
 smartFox.loadConfig("testEnvironmentConfig.xml");
 

Parameters:
configFileName - external xml configuration file name.
Since:
SmartFoxServer Pro v1.6.0
See Also:
ipAddress, port, defaultZone, debug, blueBoxIpAddress, blueBoxPort, smartConnect, SFSEvent.onConfigLoadFailure

loadConfig

public void loadConfig(java.lang.String configFileName,
                       boolean autoConnect)
Load a client configuration file.

The SmartFoxClient instance can be configured through an external xml configuration file loaded at run-time. If the autoConnect parameter is set to true, on loading completion the connect(java.lang.String) method is automatically called by the API, otherwise the SFSEvent.onConfigLoadSuccess event is dispatched. In case of loading error, the SFSEvent.onConfigLoadFailure event is fired.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).

NOTE: The external xml configuration file has the following structure: ip 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>
 

The following example shows how to load an external configuration file.

 smartFox.addEventListener(SFSEvent.onConfigLoadSuccess, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           smartFox.connect(smartFox.ipAddress, smartFox.port);
       }
   });
 smartFox.addEventListener(SFSEvent.onConfigLoadFailure, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Failed loading config file: " +
             evt.getParams().getString("message"));
       }
   });
 smartFox.loadConfig("testEnvironmentConfig.xml", false);
 

Parameters:
configFileName - external xml configuration file name.
autoConnect - a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.
Since:
SmartFoxServer Pro v1.6.0
See Also:
ipAddress, port, defaultZone, debug, blueBoxIpAddress, blueBoxPort, smartConnect, httpPort, SFSEvent.onConfigLoadSuccess, SFSEvent.onConfigLoadFailure

loadConfig

public void loadConfig(java.net.URL configFileUrl)
Load a client configuration file.

The SmartFoxClient instance can be configured through an external xml configuration file loaded at run-time. On loading completion the connect(java.lang.String) method is automatically called by the API. In case of loading error, the SFSEvent.onConfigLoadFailure event is fired.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).

NOTE: The external xml configuration file has the following structure: ip 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>
 

The following example shows how to load an external configuration file.

 smartFox.addEventListener(SFSEvent.onConfigLoadFailure, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Failed loading config file: " +
             evt.getParams().getString("message"));
       }
   });
 smartFox.loadConfig(this.getClass().getClassLoader().getResource("config.xml"));
 

Parameters:
configFileUrl - external xml configuration file URL.
Since:
SmartFoxServer Pro v1.6.0
See Also:
ipAddress, port, defaultZone, debug, blueBoxIpAddress, blueBoxPort, smartConnect, httpPort, SFSEvent.onConfigLoadFailure

loadConfig

public void loadConfig(java.net.URL configFileUrl,
                       boolean autoConnect)
Load a client configuration file.

The SmartFoxClient instance can be configured through an external xml configuration file loaded at run-time. If the autoConnect parameter is set to true, on loading completion the connect(java.lang.String) method is automatically called by the API, otherwise the SFSEvent.onConfigLoadSuccess event is dispatched. In case of loading error, the SFSEvent.onConfigLoadFailure event is fired.

NOTE: the SmartFoxClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).

NOTE: The external xml configuration file has the following structure: ip 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>
 

The following example shows how to load an external configuration file.

 smartFox.addEventListener(SFSEvent.onConfigLoadSuccess, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           smartFox.connect(smartFox.ipAddress, smartFox.port);
       }
   });
 smartFox.addEventListener(SFSEvent.onConfigLoadFailure, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Failed loading config file: " +
             evt.getParams().getString("message"));
       }
   });
 smartFox.loadConfig(this.getClass().getClassLoader().getResource("config.xml"), false);
 

Parameters:
configFileUrl - external xml configuration file URL.
autoConnect - a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.
Since:
SmartFoxServer Pro v1.6.0
See Also:
ipAddress, port, defaultZone, debug, blueBoxIpAddress, blueBoxPort, smartConnect, httpPort, SFSEvent.onConfigLoadSuccess, SFSEvent.onConfigLoadFailure

getConnectionMode

public java.lang.String getConnectionMode()
Get the current connection mode.

The following example shows how to check the current connection mode.

 smartFox.addEventListener(SFSEvent.onConnection, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Connection mode: " + smartFox.getConnectionMode());
       }
   });
 smartFox.connect("127.0.0.1", 9339)
 

Returns:
The current connection mode, expressed by one of the following constants: CONNECTION_MODE_DISCONNECTED (disconnected), CONNECTION_MODE_SOCKET (socket mode), CONNECTION_MODE_HTTP (http mode).
Since:
SmartFoxServer Pro v1.6.0
See Also:
CONNECTION_MODE_DISCONNECTED, CONNECTION_MODE_SOCKET, CONNECTION_MODE_HTTP, connect(java.lang.String)

connect

public void connect(java.lang.String ipAdr)
Establish a connection to SmartFoxServer using the default port 9339.

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.

The following example shows how to connect to SmartFoxServer.

 smartFox.connect("127.0.0.1");
 

Parameters:
ipAdr - the SmartFoxServer ip address.
Since:
SmartFoxServer Basic (except BlueBox connection) / Pro v1.x.x
See Also:
disconnect(), getConnectionMode(), smartConnect, SFSEvent.onConnection

connect

public void connect(java.lang.String ipAdr,
                    int port)
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.

The following example shows how to connect to SmartFoxServer.

 smartFox.connect("127.0.0.1");
 

Parameters:
ipAdr - the SmartFoxServer ip address.
port - the SmartFoxServer TCP port.
Since:
SmartFoxServer Basic (except BlueBox connection) / Pro v1.x.x
See Also:
disconnect(), getConnectionMode(), smartConnect, SFSEvent.onConnection

disconnect

public void disconnect()
Close the current connection to SmartFoxServer.

The following example shows how to disconnect from SmartFoxServer.

 smartFox.disconnect();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
connect(java.lang.String), SFSEvent.onConnectionLost

addBuddy

public void addBuddy(java.lang.String buddyName)
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.

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

The following example shows how to add a user to the buddy list.

 smartFox.addBuddy("jack");
 

Parameters:
buddyName - the name of the user to be added to the buddy list.
Since:
SmartFoxServer Basic (except advanced mode) / Pro v1.x.x
See Also:
buddyList, removeBuddy(java.lang.String), setBuddyBlockStatus(java.lang.String, boolean), SFSEvent.onBuddyList, SFSEvent.onBuddyListError, SFSEvent.onBuddyPermissionRequest

autoJoin

public void autoJoin()
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.

The following example shows how to join the default room in the current zone.

 smartFox.autoJoin();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
joinRoom(int), SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

clearBuddyList

@Deprecated
public void clearBuddyList()
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.

The following example shows how to clear the buddy list.

 smartFox.clearBuddyList();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
buddyList, SFSEvent.onBuddyList

createRoom

public void createRoom(java.lang.String name,
                       int maxUsers,
                       java.util.Map<java.lang.String,java.lang.Object> roomProperties)
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.

The following example shows how to create a new room.

 Map<String, Object> roomProperties = new HashMap<String, Object>();
 roomProperties.put("isGame", true);
 Map<String, RoomVariableRequest> variables = new HashMap<String, RoomVariableRequest>();
 variables.put("ogres", new RoomVariableRequest("5", SFSVariable.TYPE_NUMBER, true));
 variables.put("skeletons", new RoomVariableRequest("4", SFSVariable.TYPE_NUMBER));
 roomProperties.put("vars", variables);
 smartFox.createRoom("The Cave", 15, roomProperties);
 

Parameters:
name - the room name.
maxUsers - the maximum number of users that can join the room.
roomProperties - a Map with the following key/value pairs:
  • password: (String) a password to make the room private (optional, default: none).
  • maxSpectators: (Integer) 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: (Map<String, RoomVariableRequest>) a Map of Room Variables, as described in the setRoomVariables(java.util.Map) method documentation (optional, default: none).
  • A Room-level extension can be attached to any room during creation using the following key/value pairs (optional)
    • extensionName: (String) the name used to reference the extension (see the SmartFoxServer server-side configuration).
    • extensionScript: (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).
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onRoomAdded, SFSEvent.onCreateRoomError, SFSEvent.onUserCountChange

createRoom

public void createRoom(java.lang.String name,
                       int maxUsers,
                       java.util.Map<java.lang.String,java.lang.Object> roomProperties,
                       int roomId)
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.

The following example shows how to create a new room.

 Map<String, Object> roomProperties = new HashMap<String, Object>();
 roomProperties.put("isGame", true);
 Map<String, RoomVariableRequest> variables = new HashMap<String, RoomVariableRequest>();
 variables.put("ogres", new RoomVariableRequest("5", SFSVariable.TYPE_NUMBER, true));
 variables.put("skeletons", new RoomVariableRequest("4", SFSVariable.TYPE_NUMBER));
 roomProperties.put("vars", variables);
 smartFox.createRoom("The Cave", 15, roomProperties, 25);
 

Parameters:
name - the room name.
maxUsers - the maximum number of users that can join the room.
roomProperties - a Map with the following key/value pairs:
  • password: (String) a password to make the room private (optional, default: none).
  • maxSpectators: (Integer) 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: (Map<String, RoomVariableRequest>) a Map of Room Variables, as described in the setRoomVariables(java.util.Map) method documentation (optional, default: none).
  • A Room-level extension can be attached to any room during creation using the following key/value pairs (optional)
    • extensionName: (String) the name used to reference the extension (see the SmartFoxServer server-side configuration).
    • extensionScript: (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).
roomId - the id of the room from where the request is originated, in case the application allows multi-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onRoomAdded, SFSEvent.onCreateRoomError, SFSEvent.onUserCountChange

getAllRooms

public java.util.Map<java.lang.Integer,Room> getAllRooms()
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.

The following example shows how to retrieve the room list.

 Map<Integer, Room> rooms = smartFox.getAllRooms();
 for(Integer id : rooms.keySet())
 {
     System.out.println("Room: " + rooms.get(id).getName());
 }
 

Returns:
The list of rooms available in the current zone.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
getRoomList(), Room

getBuddyByName

public Buddy getBuddyByName(java.lang.String buddyName)
Get a buddy from the buddy list, using the buddy's username as key.

The following example shows how to retrieve a buddy from the buddy list.

 Buddy buddy = smartFox.getBuddyByName("jack");
 System.out.println("Buddy id: " + buddy.getId());
 System.out.println("Buddy name: " + buddy.getName());
 System.out.println("Is buddy online? " + (buddy.isOnline() ? "Yes" : "No"));
 System.out.println("Is buddy blocked? " + (buddy.isBlocked() ? "Yes" : "No"));
 System.out.println("Buddy Variables:"));
 // Trace all Buddy Variables
 for(String key : buddy.getVariables().keySet())
 {
     System.out.println("\t" + key + " --> " + buddy.getVariables().get(key));
 }
 

Parameters:
buddyName - the username of the buddy.
Returns:
The buddy object.
Since:
SmartFoxServer Pro v1.6.0
See Also:
buddyList, getBuddyById(int)

getBuddyById

public Buddy getBuddyById(int id)
Get a buddy from the buddy list, using the user id as key.

The following example shows how to retrieve a buddy from the buddy list.

 Buddy buddy = smartFox.getBuddyById(25);
 System.out.println("Buddy id: " + buddy.getId());
 System.out.println("Buddy name: " + buddy.getName());
 System.out.println("Is buddy online? " + (buddy.isOnline() ? "Yes" : "No"));
 System.out.println("Is buddy blocked? " + (buddy.isBlocked() ? "Yes" : "No"));
 System.out.println("Buddy Variables:"));
 // Trace all Buddy Variables
 for(String key : buddy.getVariables().keySet())
 {
     System.out.println("\t" + key + " --> " + buddy.getVariables().get(key));
 }
 

Parameters:
id - the user id of the buddy.
Returns:
The buddy object.
Since:
SmartFoxServer Pro v1.6.0
See Also:
buddyList, getBuddyByName(java.lang.String)

getBuddyRoom

public void getBuddyRoom(Buddy buddy)
Request the room id(s) of the room(s) where a buddy is currently located into.

The following example shows how to join the same room of a buddy.

 smartFox.addEventListener(SFSEvent.onBuddyRoom, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           smartFox.joinRoom(((int[])evt.getParams().get("idList"))[0]);
       }
   });
 Buddy buddy = smartFox.getBuddyByName("jack");
 smartFox.getBuddyRoom(buddy);
 

Parameters:
buddy - a buddy object taken from the buddyList.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
buddyList, SFSEvent.onBuddyRoom

getRoom

public Room getRoom(int roomId)
Get a Room object, using its id as key.

The following example shows how to retrieve a room from its id.

 Room roomObj = smartFox.getRoom(15);
 System.out.println("Room name: " + roomObj.getName() + ", max users: " + roomObj.getMaxUsers());
 

Parameters:
roomId - the id of the room.
Returns:
The Room object.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
getRoomByName(java.lang.String), getAllRooms(), getRoomList(), Room

getRoomByName

public Room getRoomByName(java.lang.String roomName)
Get a Room object, using its name as key.

The following example shows how to retrieve a room from its name.

 Room roomObj = smartFox.getRoom("The Entrance");
 System.out.println("Room name: " + roomObj.getName() + ", max users: " + roomObj.getMaxUsers());
 

Parameters:
roomName - the name of the room.
Returns:
The Room object.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
getRoom(int), getAllRooms(), getRoomList(), Room

getRoomList

public void getRoomList()
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.

The following example shows how to retrieve the room list from the server.

 smartFox.addEventListener(SFSEvent.onRoomListUpdate, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           // Dump the names of the available rooms in the current zone
                for(Integer rId : evt.getParams().get("roomList").keySet())
                    System.out.println(evt.getParams().get("roomList").get(r).getName());
       }
   });
 smartFox.getRoomList();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
getRoom(int), getRoomByName(java.lang.String), getAllRooms(), SFSEvent.onRoomListUpdate

getActiveRoom

public Room getActiveRoom()
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.

The following example shows how to retrieve the current room object.

 Room room = smartFox.getActiveRoom();
 System.out.println("Current room is: " + room.getName());
 

Returns:
the Room object of the currently active room; if the user joined more than one room, the last joined room is returned.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
activeRoomId

getRandomKey

public void getRandomKey()
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.

The following example shows how to handle the request a random key to the server.

 smartFox.addEventListener(SFSEvent.onRandomKey, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Random key received from server: " +
           evt.getParams().getString("key"));
       }
   });
 smartFox.getRandomKey();
 

Since:
SmartFoxServer Pro v1.x.x
See Also:
SFSEvent.onRandomKey

getUploadPath

public java.lang.String getUploadPath()
Get the default upload path of the embedded webserver.

The following example shows how to get the default upload path.

 String path = smartFox.getUploadPath();
 

Returns:
The http address of the default folder in which files are uploaded.
Since:
SmartFoxServer Pro v1.5.0

getVersion

public java.lang.String getVersion()
Get the SmartFoxServer Flash API version.

The following example shows how to display the SmartFoxServer API version.

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

Returns:
The current version of the SmartFoxServer client API.
Since:
SmartFoxServer Basic / Pro v1.x.x

joinRoom

public void joinRoom(int newRoom)
Join a room.

Parameters:
newRoom - the id of the room to join.

In the following example the user requests to join a room with id = 10.

 smartFox.joinRoom(10);
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

joinRoom

public void joinRoom(int newRoom,
                     java.lang.String pword,
                     boolean dontLeave)
Join a room.

In the following example the user requests to join a room with id = 12 and password = "mypassword"; SmartFoxServer will disconnect him from the previous room.

 smartFox.joinRoom(12, "mypassword", false);
 

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, "", true);
 

Parameters:
newRoom - the id of the room to join.
pword - the room's password, if it's a private room or empty String if it's not.
dontLeave - a boolean flag indicating if the current room must be left after successfully joining the new room.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

joinRoom

public void joinRoom(int newRoom,
                     java.lang.String pword,
                     boolean isSpectator,
                     boolean dontLeave)
Join a room.

In the following example the user requests to join the game room with id = 15 as spectator 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, "", true, true);
 

Parameters:
newRoom - the id of the room to join.
pword - the room's password, if it's a private room or empty String if it's not.
isSpectator - a boolean flag indicating wheter you join as a spectator or not.
dontLeave - a boolean flag indicating if the current room must be left after successfully joining the new room.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

joinRoom

public void joinRoom(int newRoom,
                     java.lang.String pword,
                     boolean isSpectator,
                     boolean dontLeave,
                     int oldRoom)
Join a room.

In the following example the user requests to join the room with id = 15 and leaves the romm with id = 25

 smartFox.joinRoom(15, "", false, false, 25);
 

Parameters:
newRoom - the id of the room to join.
pword - the room's password, if it's a private room or empty String if it's not.
isSpectator - a boolean flag indicating wheter you join as a spectator or not.
dontLeave - a boolean flag indicating if the current room must be left after successfully joining the new room.
oldRoom - the id of the room to leave.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

joinRoom

public void joinRoom(java.lang.String newRoom,
                     java.lang.String pword,
                     boolean dontLeave)
Join a room.

In the following example the user requests to join a room with name = "The Hall" and password = "mypassword"; SmartFoxServer will disconnect him from the previous room.

 smartFox.joinRoom("The Hall", "mypassword", false);
 

In the following example the user requests to join the room with name = "The Hall" 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("The Hall", "", true);
 

Parameters:
newRoom - the name of the room to join.
pword - the room's password, if it's a private room or empty String if it's not.
dontLeave - a boolean flag indicating if the current room must be left after successfully joining the new room.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

joinRoom

public void joinRoom(java.lang.String newRoom,
                     java.lang.String pword,
                     boolean isSpectator,
                     boolean dontLeave)
Join a room.

In the following example the user requests to join the game room with name = "The Hall" as spectator 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("The Hall", "", true, true);
 

Parameters:
newRoom - the name of the room to join.
pword - the room's password, if it's a private room or empty String if it's not.
isSpectator - a boolean flag indicating wheter you join as a spectator or not.
dontLeave - a boolean flag indicating if the current room must be left after successfully joining the new room.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

joinRoom

public void joinRoom(java.lang.String newRoom,
                     java.lang.String pword,
                     boolean isSpectator,
                     boolean dontLeave,
                     int oldRoom)
Join a room.

In the following example the user requests to join the room with name= "The Hall" and leaves the romm with id = 25

 smartFox.joinRoom("The Hall", "", false, false, 25);
 

Parameters:
newRoom - the name of the room to join.
pword - the room's password, if it's a private room or empty String if it's not.
isSpectator - a boolean flag indicating wheter you join as a spectator or not.
dontLeave - a boolean flag indicating if the current room must be left after successfully joining the new room.
oldRoom - the id of the room to leave.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onJoinRoom, SFSEvent.onJoinRoomError

leaveRoom

public void leaveRoom(int roomId)
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).

The following example shows how to make a user leave a room.

 smartFox.leaveRoom(15);
 

Parameters:
roomId - the id of the room to leave.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
joinRoom(int), SFSEvent.onRoomLeft

loadBuddyList

public void loadBuddyList()
Load the buddy list for the current user.

The following example shows how to load the current user's buddy list.

 smartFox.addEventListener(SFSEvent.onBuddyList, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           for(Buddy buddy : smartFox.buddyList)
           {
 
               // Trace buddy properties
               System.out.println("Buddy id: " + buddy.getId());
               System.out.println("Buddy name: " + buddy.getName());
               System.out.println("Is buddy online? " + (buddy.isOnline() ? "Yes" : "No"));
               System.out.println("Is buddy blocked? " + (buddy.isBlocked() ? "Yes" : "No"));
 
               // Trace all Buddy Variables
               for(String key : buddy.getVariables().keySet())
               {
                   System.out.println("\t" + key + " --> " + buddy.getVariables().get(key));
               }
           }
       }
   });
 smartFox.loadBuddyList();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
buddyList, SFSEvent.onBuddyList, SFSEvent.onBuddyListError

login

public void login(java.lang.String zone,
                  java.lang.String name,
                  java.lang.String pass)
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.

The following example shows how to login into a zone.

 smartFox.addEventListener(SFSEvent.onLogin, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           if(evt.getParams().getBool("success"))
           {
               System.out.println("Successfully logged in as " + evt.getParams().getString("name"));
           }
           else
           {
               System.out.println("Zone login error; the following error occurred: " + evt.getParams().getString("error"));
           }
       }
   });
 smartFox.login("simpleChat", "jack", "");
 

Parameters:
zone - the name of the zone to log into.
name - the user name.
pass - the user password. Empty String if no password.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
logout(), SFSEvent.onLogin

logout

public void logout()
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.

The following example shows how to logout from a zone.

 smartFox.addEventListener(SFSEvent.onLogout, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("Logged out successfully");
       }
   });
 smartFox.logout();
 

Since:
SmartFoxServer Pro v1.5.5
See Also:
login(java.lang.String, java.lang.String, java.lang.String), SFSEvent.onLogout

removeBuddy

public void removeBuddy(java.lang.String buddyName)
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.

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

The following example shows how to remove a user from the buddy list.

 String buddyName = "jack";
 smartFox.removeBuddy(buddyName);
 

Parameters:
buddyName - the name of the user to be removed from the buddy list.
Since:
SmartFoxServer Basic (except advanced mode) / Pro v1.x.x
See Also:
buddyList, addBuddy(java.lang.String), SFSEvent.onBuddyList

roundTripBench

public void roundTripBench()
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).

The following example shows how to check the average network lag time.

 smartFox.addEventListener(SFSEvent.onRoundTripResponse, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           long lag = (Long)evt.getParams().get("elapsed");
           System.out.println("Lag: " + lag + "milliseconds.");
       }
   });
 smartFox.roundTripBench();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
SFSEvent.onRoundTripResponse

sendBuddyPermissionResponse

public void sendBuddyPermissionResponse(boolean allowBuddy,
                                        java.lang.String targetBuddy)
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.

The following example shows how to grant permission to be added to a buddy list once request is received.

 smartFox.addEventListener(SFSEvent.onBuddyPermissionRequest, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           smartFox.sendBuddyPermissionResponse(true, evt.getParams().getString("sender"));
       }
   });
 

Parameters:
allowBuddy - true to grant permission, false to refuse to be added to the requester's buddy list.
targetBuddy - the username of the requester.
Since:
SmartFoxServer Pro v1.6.0
See Also:
addBuddy(java.lang.String), SFSEvent.onBuddyPermissionRequest

sendPublicMessage

public void sendPublicMessage(java.lang.String message)
Send a public message.

The message is broadcasted to all users in the current room, including the sender.

The following example shows how to send and receive a public message.

 smartFox.addEventListener(SFSEvent.onPublicMessage, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("User " +
             ((User)evt.getParams().getObj("sender")).getName() +
             " said: " + evt.getParams().getString("message"));
       }
   });
 smartFox.sendPublicMessage("Hello world!");
 

Parameters:
message - the text of the public message.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendPrivateMessage(java.lang.String, int), SFSEvent.onPublicMessage

sendPublicMessage

public void sendPublicMessage(java.lang.String message,
                              int roomId)
Send a public message.

The message is broadcasted to all users in the current room, including the sender.

The following example shows how to send and receive a public message.

 smartFox.addEventListener(SFSEvent.onPublicMessage, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("User " +
             ((User)evt.getParams().getObj("sender")).getName() +
             " said: " + evt.getParams().getString("message"));
       }
   });
 smartFox.sendPublicMessage("Hello world!", 25);
 

Parameters:
message - the text of the public message.
roomId - the id of the target room, in case of multi-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendPrivateMessage(java.lang.String, int), SFSEvent.onPublicMessage

sendPrivateMessage

public void sendPrivateMessage(java.lang.String message,
                               int recipientId)
Send a private message to a user.

The message is broadcasted to the recipient and the sender.

The following example shows how to send and receive a private message.

 smartFox.addEventListener(SFSEvent.onPrivateMessage, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("User " +
             ((User)evt.getParams().getObj("sender")).getName() +
             " sent the following private message: " + evt.getParams().getString("message"));
       }
   });
 smartFox.sendPrivateMessage("Hello world!");
 

Parameters:
message - the text of the private message.
recipientId - the id of the recipient user.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendPublicMessage(java.lang.String), SFSEvent.onPrivateMessage

sendPrivateMessage

public void sendPrivateMessage(java.lang.String message,
                               int recipientId,
                               int roomId)
Send a private message to a user.

The message is broadcasted to the recipient and the sender.

The following example shows how to send and receive a private message.

 smartFox.addEventListener(SFSEvent.onPublicMessage, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           System.out.println("User " +
             ((User)evt.getParams().getObj("sender")).getName() +
             " sent the following private message: " + evt.getParams().getString("message"));
       }
   });
 smartFox.sendPrivateMessage("Hello world!", 25);
 

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.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendPublicMessage(java.lang.String), SFSEvent.onPrivateMessage

sendModeratorMessage

public void sendModeratorMessage(java.lang.String message,
                                 java.lang.String type,
                                 int id)
Send a Moderator message to the current zone, the current room or a specific user in the current room.

The following example shows how to send a Moderator message.

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

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(java.lang.String, java.lang.String, java.lang.String) 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).
Since:
SmartFoxServer Pro v1.4.5
See Also:
login(java.lang.String, java.lang.String, java.lang.String), MODMSG_TO_USER, MODMSG_TO_ROOM, MODMSG_TO_ZONE, SFSEvent.onModeratorMessage

sendObject

public void sendObject(SFSObject obj)
Send an 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.

The following example shows how to send a simple object to the other users.

 SFSObject move = new SFSObject();
 move.putNumber("x", 150);
 move.putNumber("y", 250);
 move.putNumber("speed", 8);
 smartFox.sendObject(move);
 

Parameters:
obj - the object to be sent. Supported classes are: Boolean, Double, String, SFSObject.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendObjectToGroup(it.gotoandplay.smartfoxclient.data.SFSObject, int[]), SFSEvent.onObjectReceived

sendObject

public void sendObject(SFSObject obj,
                       int roomId)
Send an 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.

The following example shows how to send a simple object to the other users.

 SFSObject move = new SFSObject();
 move.putNumber("x", 150);
 move.putNumber("y", 250);
 move.putNumber("speed", 8);
 smartFox.sendObject(move, 25);
 

Parameters:
obj - the object to be sent. Supported classes are: Boolean, Double, String, SFSObject.
roomId - the id of the target room, in case of multi-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendObjectToGroup(it.gotoandplay.smartfoxclient.data.SFSObject, int[]), SFSEvent.onObjectReceived

sendObjectToGroup

public void sendObjectToGroup(SFSObject obj,
                              int[] userList)
Send an Actionscript object to a group of users in the room.

See sendObject(it.gotoandplay.smartfoxclient.data.SFSObject) for more info.

The following example shows how to send a simple object with primitive data to two users.

 SFSObject move = new SFSObject();
 move.putNumber("x", 150);
 move.putNumber("y", 250);
 move.putNumber("speed", 8);
 smartFox.sendObjectToGroup(move, new int[]{11, 12});
 

Parameters:
obj - the object to be sent. Supported classes are: Boolean, Double, String, SFSObject.
userList - an array containing the id(s) of the recipients.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendObject(it.gotoandplay.smartfoxclient.data.SFSObject), SFSEvent.onObjectReceived

sendObjectToGroup

public void sendObjectToGroup(SFSObject obj,
                              int[] userList,
                              int roomId)
Send an Actionscript object to a group of users in the room.

See sendObject(it.gotoandplay.smartfoxclient.data.SFSObject) for more info.

The following example shows how to send a simple object with primitive data to two users.

 SFSObject move = new SFSObject();
 params.put("type", "bullet");
 move.putNumber("x", 150);
 move.putNumber("y", 250);
 move.putNumber("speed", 8);
 smartFox.sendObjectToGroup(move, new int[]{11, 12}, 25);
 

Parameters:
obj - the object to be sent. Supported classes are: Boolean, Double, String, SFSObject.
roomId - the id of the target room, in case of multi-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
sendObject(it.gotoandplay.smartfoxclient.data.SFSObject), SFSEvent.onObjectReceived

sendXtMessage

public void sendXtMessage(java.lang.String xtName,
                          java.lang.String cmd,
                          SFSObject paramObj)
Send a request to a server side extension using XML protocol.

NOTE: the use JSON instead of XML is highly recommended, as it can save a lot of bandwidth.

The following example shows how to notify a multiplayer game server-side extension that a game action occurred.

 // A bullet is being fired
 SFSObject params = new SFSObject();
 params.put("type", "bullet");
 params.putNumber("posx", 100);
 params.putNumber("posy", 200);
 params.putNumber("speed", 10);
 params.putNumber("angle", 45);
 // Invoke "fire" command on the extension called "gameExt", using XML protocol
 smartFox.sendXtMessage("gameExt", "fire", params);
 

Parameters:
xtName - the name of the extension (see also the createRoom(java.lang.String, int, java.util.Map) 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). Supported classes are: Boolean, Double, String, SFSObject.
Since:
SmartFoxServer Pro v1.x.x
See Also:
XTMSG_TYPE_XML, SFSEvent.onExtensionResponse

sendXtMessage

public void sendXtMessage(java.lang.String xtName,
                          java.lang.String cmd,
                          SFSObject paramObj,
                          int roomId)
Send a request to a server side extension using XML protocol.

NOTE: the use JSON instead of XML is highly recommended, as it can save a lot of bandwidth.

The following example shows how to notify a multiplayer game server-side extension that a game action occurred.

 // A bullet is being fired
 SFSObject params = new SFSObject();
 params.put("type", "bullet");
 params.putNumber("posx", 100);
 params.putNumber("posy", 200);
 params.putNumber("speed", 10);
 params.putNumber("angle", 45);
 // Invoke "fire" command on the extension called "gameExt", using XML protocol
 smartFox.sendXtMessage("gameExt", "fire", params, 25);
 

Parameters:
xtName - the name of the extension (see also the createRoom(java.lang.String, int, java.util.Map) 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). Supported classes are: Boolean, Double, String, SFSObject.
roomId - the id of the room where the request was originated, in case of multi-room join.
Since:
SmartFoxServer Pro v1.x.x
See Also:
XTMSG_TYPE_XML, SFSEvent.onExtensionResponse

sendXtMessage

public void sendXtMessage(java.lang.String xtName,
                          java.lang.String cmd,
                          org.json.JSONObject paramObj)
Send a request to a server side extension using JSON protocol.

NOTE: the use JSON instead of XML is highly recommended, as it can save a lot of bandwidth.

The following example shows how to notify a multiplayer game server-side extension that a game action occurred.

 // A bullet is being fired
 try
 {
     JSONObject params = new JSONObject("{ "type" : "bullet", "posx" : 100, "posy" : 200, "speed" : 10, "angle" : 45 }");
     // Invoke "fire" command on the extension called "gameExt", using JSON protocol
     smartFox.sendXtMessage("gameExt", "fire", params);
 }
 catch(JSONException ex)
 {
     ex.printStackTrace();
 }
 

Parameters:
xtName - the name of the extension (see also the createRoom(java.lang.String, int, java.util.Map) 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).
Since:
SmartFoxServer Pro v1.x.x
See Also:
XTMSG_TYPE_JSON, SFSEvent.onExtensionResponse

sendXtMessage

public void sendXtMessage(java.lang.String xtName,
                          java.lang.String cmd,
                          org.json.JSONObject paramObj,
                          int roomId)
Send a request to a server side extension using JSON protocol.

NOTE: the use JSON instead of XML is highly recommended, as it can save a lot of bandwidth.

The following example shows how to notify a multiplayer game server-side extension that a game action occurred.

 // A bullet is being fired
 try
 {
     JSONObject params = new JSONObject("{ "type" : "bullet", "posx" : 100, "posy" : 200, "speed" : 10, "angle" : 45 }");
     // Invoke "fire" command on the extension called "gameExt", using JSON protocol
     smartFox.sendXtMessage("gameExt", "fire", params);
 }
 catch(JSONException ex)
 {
     ex.printStackTrace();
 }
 

Parameters:
xtName - the name of the extension (see also the createRoom(java.lang.String, int, java.util.Map) 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).
roomId - the id of the room where the request was originated, in case of multi-room join.
Since:
SmartFoxServer Pro v1.x.x
See Also:
XTMSG_TYPE_JSON, SFSEvent.onExtensionResponse

sendXtMessage

public void sendXtMessage(java.lang.String xtName,
                          java.lang.String cmd,
                          java.lang.String[] params)
Send a request to a server side extension using String protocol.

NOTE: The String-based protocol can be very useful for realtime applications/games where reducing the amount of data is the highest priority.

The following example shows how to notify a multiplayer game server-side extension that a game action occurred.

 // A bullet is being fired
 
 // The array contains the type, x and y position, speed and the angle.
 String[] params = {"bullet", "100", "200", "10", "45"};
 
 // Invoke "fire" command on the extension called "gameExt", using String protocol
 smartFox.sendXtMessage("gameExt", "fire", params);
 

Parameters:
xtName - the name of the extension (see also the createRoom(java.lang.String, int, java.util.Map) method).
cmd - the name of the action/command to execute in the extension.
params - an array that contains the data to be passed to the extension (set to empty array if no data is required).
Since:
SmartFoxServer Pro v1.x.x
See Also:
XTMSG_TYPE_STR, SFSEvent.onExtensionResponse

sendXtMessage

public void sendXtMessage(java.lang.String xtName,
                          java.lang.String cmd,
                          java.lang.String[] params,
                          int roomId)
Send a request to a server side extension using String protocol.

NOTE: The String-based protocol can be very useful for realtime applications/games where reducing the amount of data is the highest priority.

The following example shows how to notify a multiplayer game server-side extension that a game action occurred.

 // A bullet is being fired
 
 // The array contains the x and y position, speed and the angle.
 String[] params = {"bullet", "100", "200", "10", "45"};
 
 // Invoke "fire" command on the extension called "gameExt", using String protocol
 smartFox.sendXtMessage("gameExt", "fire", params, 25);
 

Parameters:
xtName - the name of the extension (see also the createRoom(java.lang.String, int, java.util.Map) method).
cmd - the name of the action/command to execute in the extension.
params - an array that contains the data to be passed to the extension (set to empty array if no data is required).
roomId - the id of the room where the request was originated, in case of multi-room join.
Since:
SmartFoxServer Pro v1.x.x
See Also:
XTMSG_TYPE_STR, SFSEvent.onExtensionResponse

setBuddyBlockStatus

public void setBuddyBlockStatus(java.lang.String buddyName,
                                boolean status)
Block or unblock a user in the buddy list.

When a buddy is blocked, SmartFoxServer does not deliver private messages from/to that user.

The following example shows how to block a user from the buddy list.

 smartFox.setBuddyBlockStatus("jack", true);
 

Parameters:
buddyName - the name of the buddy to be blocked or unblocked.
status - true to block the buddy, false to unblock the buddy.
Since:
SmartFoxServer Pro v1.6.0
See Also:
buddyList

setBuddyVariables

public void setBuddyVariables(java.util.Map<java.lang.String,java.lang.String> varList)
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).

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(java.util.Map) method), the myBuddyVars list 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 list by means of the getBuddyById(int) or getBuddyByName(java.lang.String) 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.

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.

 Map<String, String> bVars = new HashMap();
 bVars.put("status", "away");
 bVars.put("track", "One Of These Days");
 bVars.put("$rank", "guru");
 smartFox.setBuddyVariables(bVars);
 

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.
Since:
SmartFoxServer Basic (except advanced mode) / Pro v1.x.x
See Also:
myBuddyVars, SFSEvent.onBuddyListUpdate

setRoomVariables

public void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars)
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.

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, false, true);
 rVars.put("score", variable);
 smartFox.setRoomVariables(rVars);
 

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, false, true);
 rVars.put("score", variable);
 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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest bestTime = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, true);
 rVars.put("bestTime", bestTime);
 RoomVariableRequest bestLap = new RoomVariableRequest("120", SFSVariable.TYPE_NUMBER);
 rVars.put("bestLap", bestLap);
 smartFox.setRoomVariables(rVars);
 

The following example shows how to delete a Room Variable called "bestTime" by setting its value to null.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest(null, SFSVariable.TYPE_NULL);
 rVars.put("bestTime", variable);
 smartFox.setRoomVariables(rVars);
 

The following example shows how to send an array-like set of data without consuming too much bandwidth.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 String[] names = {"john", "dave", "sam"};
 for(int i = 0; i < names.lenght; i++)
 {
     RoomVariableRequest variable = new RoomVariableRequest(names[i], SFSVariable.TYPE_STRING);
     rVars.put("name" + i, variable);
 }
 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, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           Set<String> changedVars = (Set<String>)evt.getParams().get("changedVars");
           Room room = (Room)evt.getParams().get("room");
           for(String v : changedVars)
           {
               System.out.println(v + " room variable was updated; new value is: " + room.getVariable(v).getValue());
           }
       }
   });
 

Parameters:
vars - Map containing the room variables name as key and the room variables as value.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
Room.getVariable(java.lang.String), Room.getVariables(), SFSEvent.onRoomVariablesUpdate

setRoomVariables

public void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars,
                             int roomId)
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.

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, false, true);
 rVars.put("score", variable);
 smartFox.setRoomVariables(rVars, 25);
 

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, false, true);
 rVars.put("score", variable);
 smartFox.setRoomVariables(rVars, 25);
 

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest bestTime = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, true);
 rVars.put("bestTime", bestTime);
 RoomVariableRequest bestLap = new RoomVariableRequest("120", SFSVariable.TYPE_NUMBER);
 rVars.put("bestLap", bestLap);
 smartFox.setRoomVariables(rVars, 25);
 

The following example shows how to delete a Room Variable called "bestTime" by setting its value to null.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest(null, SFSVariable.TYPE_NULL);
 rVars.put("bestTime", variable);
 smartFox.setRoomVariables(rVars, 25);
 

The following example shows how to send an array-like set of data without consuming too much bandwidth.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 String[] names = {"john", "dave", "sam"};
 for(int i = 0; i < names.lenght; i++)
 {
     RoomVariableRequest variable = new RoomVariableRequest(names[i], SFSVariable.TYPE_STRING);
     rVars.put("name" + i, variable);
 }
 smartFox.setRoomVariables(rVars, 25);
 

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, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           Set<String> changedVars = (Set<String>)evt.getParams().get("changedVars");
           Room room = (Room)evt.getParams().get("room");
           for(String v : changedVars)
           {
               System.out.println(v + " room variable was updated; new value is: " + room.getVariable(v).getValue());
           }
       }
   });
 

Parameters:
vars - Map containing the room variables name as key and the room variables as value.
roomId - the id of the room where the variables should be set, in case of molti-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
Room.getVariable(java.lang.String), Room.getVariables(), SFSEvent.onRoomVariablesUpdate

setRoomVariables

public void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars,
                             int roomId,
                             boolean setOwnership)
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.

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, false, true);
 rVars.put("score", variable);
 smartFox.setRoomVariables(rVars, activeRoomId, true);
 

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, false, true);
 rVars.put("score", variable);
 smartFox.setRoomVariables(rVars, activeRoomId, true);
 

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest bestTime = new RoomVariableRequest("2500", SFSVariable.TYPE_NUMBER, true);
 rVars.put("bestTime", bestTime);
 RoomVariableRequest bestLap = new RoomVariableRequest("120", SFSVariable.TYPE_NUMBER);
 rVars.put("bestLap", bestLap);
 smartFox.setRoomVariables(rVars, activeRoomId, true);
 

The following example shows how to delete a Room Variable called "bestTime" by setting its value to null.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest variable = new RoomVariableRequest(null, SFSVariable.TYPE_NULL);
 rVars.put("bestTime", variable);
 smartFox.setRoomVariables(rVars, activeRoomId, true);
 

The following example shows how to send an array-like set of data without consuming too much bandwidth.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 String[] names = {"john", "dave", "sam"};
 for(int i = 0; i < names.lenght; i++)
 {
     RoomVariableRequest variable = new RoomVariableRequest(names[i], SFSVariable.TYPE_STRING);
     rVars.put("name" + i, variable);
 }
 smartFox.setRoomVariables(rVars, activeRoomId, true);
 

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, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           Set<String> changedVars = (Set<String>)evt.getParams().get("changedVars");
           Room room = (Room)evt.getParams().get("room");
           for(String v : changedVars)
           {
               System.out.println(v + " room variable was updated; new value is: " + room.getVariable(v).getValue());
           }
       }
   });
 

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.

 Map<String, RoomVariableRequest> rVars = new HashMap<String, RoomVariableRequest>();
 RoomVariableRequest shipPosX = new RoomVariableRequest("100", SFSVariable.TYPE_NUMBER);
 rVars.put("shipPosX", shipPosX);
 RoomVariableRequest shipPosY = new RoomVariableRequest("200", SFSVariable.TYPE_NUMBER);
 rVars.put("shipPosY", shipPosY);
 smartFox.setRoomVariables(rVars, activeRoomId, false);
 

Parameters:
vars - Map containing the room variables name as key and the room variables as value.
roomId - the id of the room where the variables should be set, in case of molti-room join.
setOwnership - false to prevent the Room Variable change ownership when its value is modified by another user.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
Room.getVariable(java.lang.String), Room.getVariables(), SFSEvent.onRoomVariablesUpdate

setUserVariables

public void setUserVariables(java.util.Map<java.lang.String,SFSVariable> vars)
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.

The following example shows how to save the user data (avatar name and position) in an avatar chat application.

 Map<String, SFSVariable> uVars = new HashMap<String, SFSVariable>();
 uVars.put("myAvatar", new SFSVariable("Homer", SFSVariable.TYPE_STRING));
 uVars.put("posx", new SFSVariable("100", SFSVariable.TYPE_NUMBER));
 uVars.put("posy", new SFSVariable("200", SFSVariable.TYPE_NUMBER));
 smartFox.setUserVariables(uVars);
 

Parameters:
vars - Map containing the user variables name as key and the room variables as value.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
User.getVariable(java.lang.String), User.getVariables(), SFSEvent.onUserVariablesUpdate

setUserVariables

public void setUserVariables(java.util.Map<java.lang.String,SFSVariable> vars,
                             int roomId)
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.

The following example shows how to save the user data (avatar name and position) in an avatar chat application.

 Map<String, SFSVariable> uVars = new HashMap<String, SFSVariable>();
 uVars.put("myAvatar", new SFSVariable("Homer", SFSVariable.TYPE_STRING));
 uVars.put("posx", new SFSVariable("100", SFSVariable.TYPE_NUMBER));
 uVars.put("posy", new SFSVariable("200", SFSVariable.TYPE_NUMBER));
 smartFox.setUserVariables(uVars, 25);
 

Parameters:
vars - Map containing the user variables name as key and the room variables as value.
roomId - the room id where the request was originated, in case of molti-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
User.getVariable(java.lang.String), User.getVariables(), SFSEvent.onUserVariablesUpdate

switchSpectator

public void switchSpectator()
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.

The following example shows how to turn a spectator into a player.

 smartFox.addEventListener(SFSEvent.onSpectatorSwitched, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           if(evt.getParams().getBool("success"))
           {
               System.out.println("You have been turned into a player; your player id is " + evt.getParams().get("newId"));
           }
           else
           {
               System.out.println("The attempt to switch from spectator to player failed");
           }
       }
   });
 smartFox.switchSpectator();
 

Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
User.isSpectator(), SFSEvent.onSpectatorSwitched

switchSpectator

public void switchSpectator(int roomId)
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.

The following example shows how to turn a spectator into a player.

 smartFox.addEventListener(SFSEvent.onSpectatorSwitched, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           if(evt.getParams().getBool("success"))
           {
               System.out.println("You have been turned into a player; your player id is " + evt.getParams().get("newId"));
           }
           else
           {
               System.out.println("The attempt to switch from spectator to player failed");
           }
 
           smartFox.switchSpectator(25);
       }
   });
 

Parameters:
roomId - the id of the room where the spectator should be switched, in case of molti-room join.
Since:
SmartFoxServer Basic / Pro v1.x.x
See Also:
User.isSpectator(), SFSEvent.onSpectatorSwitched

switchPlayer

public void switchPlayer()
Turn a player inside a game room into a spectator.

All players have their player id property set to a value > 0; when a spectator becomes a player, his playerId is set to -1.

If the user joined more than one room use switchPlayer(int) instead.

The switch operation is successful only if at least one spectator slot is available in the room.

The following example shows how to turn a spectator into a player.

 smartFox.addEventListener(SFSEvent.onPlayerSwitched, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           if(evt.getParams().getBool("success"))
           {
               System.out.println("You have been turned into a player; your id is " + evt.getParams().get("newId"));
           }
           else
           {
               System.out.println("The attempt to switch from spectator to player failed");
           }

           smartFox.switchPlayer();
       }
   });
 

Since:
SmartFoxServer Pro v1.6.6
See Also:
switchPlayer(int), User.isSpectator(), SFSEvent.onPlayerSwitched

switchPlayer

public void switchPlayer(int roomId)
Turn a player inside a game room into a spectator.

All players have their player id property set to a value > 0; when a spectator becomes a player, his playerId is set to -1.

The switch operation is successful only if at least one spectator slot is available in the room.

The following example shows how to turn a spectator into a player.

 smartFox.addEventListener(SFSEvent.onPlayerSwitched, new ISFSEventHandler()
   {
       public void handleEvent(SFSEvent evt)
       {
           if(evt.getParams().getBool("success"))
           {
               System.out.println("You have been turned into a player; your id is " + evt.getParams().get("newId"));
           }
           else
           {
               System.out.println("The attempt to switch from spectator to player failed");
     7      }

           smartFox.switchPlayer(35);
       }
   });
 

Parameters:
roomId - the id of the room where the player should be switched to spectator.
Since:
SmartFoxServer Pro v1.6.6
See Also:
User.isSpectator(), SFSEvent.onPlayerSwitched

__logout

public void __logout()

sendString

public void sendString(java.lang.String strMessage)

sendJson

public void sendJson(java.lang.String jsMessage)

getBenchStartTime

public long getBenchStartTime()

clearRoomList

public void clearRoomList()

handleEvent

public void handleEvent(SFSEvent event)
Description copied from interface: ISFSEventListener
Handles SmartFoxServer event.

Specified by:
handleEvent in interface ISFSEventListener
Parameters:
event - the event that is fired.

onConnect

public void onConnect(boolean success)
Specified by:
onConnect in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler

onClose

public void onClose()
Specified by:
onClose in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler

onError

public void onError(java.lang.Exception e)
Specified by:
onError in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler

onData

public void onData(java.lang.String message)
Specified by:
onData in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler