|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objectit.gotoandplay.smartfoxclient.SFSEventDispatcher
it.gotoandplay.smartfoxclient.SmartFoxClient
public class SmartFoxClient
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.
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 |
|---|
public static final java.lang.String MODMSG_TO_USER
The Moderator message is sent to a single user.
sendModeratorMessage(java.lang.String, java.lang.String, int),
Constant Field Valuespublic static final java.lang.String MODMSG_TO_ROOM
The Moderator message is sent to all the users in a room.
sendModeratorMessage(java.lang.String, java.lang.String, int),
Constant Field Valuespublic static final java.lang.String MODMSG_TO_ZONE
The Moderator message is sent to all the users in a zone.
sendModeratorMessage(java.lang.String, java.lang.String, int),
Constant Field Valuespublic static final java.lang.String XTMSG_TYPE_XML
SFSEvent.onExtensionResponse,
Constant Field Valuespublic static final java.lang.String XTMSG_TYPE_STR
SFSEvent.onExtensionResponse,
Constant Field Valuespublic static final java.lang.String XTMSG_TYPE_JSON
SFSEvent.onExtensionResponse,
Constant Field Valuespublic static final java.lang.String CONNECTION_MODE_DISCONNECTED
The client is currently disconnected from SmartFoxServer.
getConnectionMode(),
Constant Field Valuespublic static final java.lang.String CONNECTION_MODE_SOCKET
The client is currently connected to SmartFoxServer via socket.
getConnectionMode(),
Constant Field Valuespublic static final java.lang.String CONNECTION_MODE_HTTP
The client is currently connected to SmartFoxServer via http.
getConnectionMode(),
Constant Field Valuespublic volatile java.lang.String ipAddress
connect(java.lang.String)public volatile int port
connect(java.lang.String)public volatile java.lang.String defaultZone
loadConfig(java.lang.String)public volatile java.lang.String blueBoxIpAddress
smartConnect,
loadConfig(java.lang.String)public volatile int blueBoxPort
smartConnect,
loadConfig(java.lang.String)public volatile boolean smartConnect
The default value is true.
loadConfig(java.lang.String)public volatile java.util.List<Buddy> buddyList
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));
}
}
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.onBuddyListUpdatepublic volatile java.util.Map<java.lang.String,java.lang.String> myBuddyVars
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));
}
setBuddyVariables(java.util.Map) ,
getBuddyById(int),
getBuddyByName(java.lang.String),
SFSEvent.onBuddyList,
SFSEvent.onBuddyListUpdatepublic volatile int myUserId
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);
myUserNamepublic volatile java.lang.String myUserName
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);
myUserId,
login(java.lang.String, java.lang.String, java.lang.String)public volatile int playerId
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);
Room.getMyPlayerIndex(),
Room.isGame()public volatile boolean amIModerator
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");
sendModeratorMessage(java.lang.String, java.lang.String, int)public volatile int activeRoomId
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());
getActiveRoom()public volatile boolean changingRoom
public volatile int httpPort
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);
| Constructor Detail |
|---|
public SmartFoxClient(boolean debug)
debug - turn on the debug messages.| Method Detail |
|---|
public char getRawProtocolSeparator()
XTMSG_TYPE_STR,
setRawProtocolSeparator(char),
sendXtMessage(java.lang.String, java.lang.String, it.gotoandplay.smartfoxclient.data.SFSObject)public void setRawProtocolSeparator(char value)
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('|');
value - the character used as separator for the String (raw) protocol.XTMSG_TYPE_STR,
sendXtMessage(java.lang.String, java.lang.String, it.gotoandplay.smartfoxclient.data.SFSObject)public boolean isConnected()
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"));
true if the current user is connected to the server,
false if the current user is not connected to the server.public void setConnected(boolean connected)
connected flag.
connected - true if the current user is connected to the server,
false if the current user is not connected to the server.public int getHttpPollSpeed()
smartConnectpublic void setHttpPollSpeed(int pollSpeed)
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.
pollSpeed - The minimum interval between two polling requestssmartConnectpublic boolean isDebug()
true if the debug messages are enabled,
otherwise returns false.
true if the debug messages are enabled, otherwise false.public void setDebug(boolean debug)
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);
SFSEvent.onDebugMessagepublic java.util.logging.Logger getLogger()
Logger used to log the SmatFoxCLient debug messages.
Logger used to log the SmatFoxCLient debug messages.setDebug(boolean)public void loadConfig(java.lang.String configFileName)
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");
configFileName - external xml configuration file name.ipAddress,
port,
defaultZone,
debug,
blueBoxIpAddress,
blueBoxPort,
smartConnect,
SFSEvent.onConfigLoadFailure
public void loadConfig(java.lang.String configFileName,
boolean autoConnect)
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);
configFileName - external xml configuration file name.autoConnect - a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.ipAddress,
port,
defaultZone,
debug,
blueBoxIpAddress,
blueBoxPort,
smartConnect,
httpPort,
SFSEvent.onConfigLoadSuccess,
SFSEvent.onConfigLoadFailurepublic void loadConfig(java.net.URL configFileUrl)
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"));
configFileUrl - external xml configuration file URL.ipAddress,
port,
defaultZone,
debug,
blueBoxIpAddress,
blueBoxPort,
smartConnect,
httpPort,
SFSEvent.onConfigLoadFailure
public void loadConfig(java.net.URL configFileUrl,
boolean autoConnect)
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);
configFileUrl - external xml configuration file URL.autoConnect - a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.ipAddress,
port,
defaultZone,
debug,
blueBoxIpAddress,
blueBoxPort,
smartConnect,
httpPort,
SFSEvent.onConfigLoadSuccess,
SFSEvent.onConfigLoadFailurepublic java.lang.String getConnectionMode()
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)
CONNECTION_MODE_DISCONNECTED (disconnected),
CONNECTION_MODE_SOCKET (socket mode),
CONNECTION_MODE_HTTP (http mode).CONNECTION_MODE_DISCONNECTED,
CONNECTION_MODE_SOCKET,
CONNECTION_MODE_HTTP,
connect(java.lang.String)public void connect(java.lang.String ipAdr)
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");
ipAdr - the SmartFoxServer ip address.disconnect(),
getConnectionMode(),
smartConnect,
SFSEvent.onConnection
public void connect(java.lang.String ipAdr,
int port)
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");
ipAdr - the SmartFoxServer ip address.port - the SmartFoxServer TCP port.disconnect(),
getConnectionMode(),
smartConnect,
SFSEvent.onConnectionpublic void disconnect()
The following example shows how to disconnect from SmartFoxServer.
smartFox.disconnect();
connect(java.lang.String),
SFSEvent.onConnectionLostpublic void addBuddy(java.lang.String buddyName)
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.
<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");
buddyName - the name of the user to be added to the buddy list.buddyList,
removeBuddy(java.lang.String),
setBuddyBlockStatus(java.lang.String, boolean),
SFSEvent.onBuddyList,
SFSEvent.onBuddyListError,
SFSEvent.onBuddyPermissionRequestpublic void autoJoin()
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();
joinRoom(int),
SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError@Deprecated public void clearBuddyList()
The following example shows how to clear the buddy list.
smartFox.clearBuddyList();
buddyList,
SFSEvent.onBuddyList
public void createRoom(java.lang.String name,
int maxUsers,
java.util.Map<java.lang.String,java.lang.Object> roomProperties)
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);
name - the room name.maxUsers - the maximum number of users that can join the room.roomProperties - a Map with the following key/value pairs:
String) a password to make the room private (optional, default: none).
Integer) in game rooms only, the maximum number of
spectators that can join the room (optional, default value: 0).
Boolean) if true, the room is a game room
(optional, default value: false).
Boolean) if true and in case of game room,
the new room is joined after creation
(optional, default value: true).
Boolean) if true and in case of game room,
allows to join the new room as spectator
(optional, default value: false).
Boolean) if true, the new room will receive the
SFSEvent.onUserCountChange notifications
(optional, default recommended value: false).
Map<String, RoomVariableRequest>) a Map of Room Variables,
as described in the setRoomVariables(java.util.Map) method documentation
(optional, default: none).
String) the name used to reference the extension
(see the SmartFoxServer server-side configuration).
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).
SFSEvent.onRoomAdded,
SFSEvent.onCreateRoomError,
SFSEvent.onUserCountChange
public void createRoom(java.lang.String name,
int maxUsers,
java.util.Map<java.lang.String,java.lang.Object> roomProperties,
int roomId)
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);
name - the room name.maxUsers - the maximum number of users that can join the room.roomProperties - a Map with the following key/value pairs:
String) a password to make the room private (optional, default: none).
Integer) in game rooms only, the maximum number of
spectators that can join the room (optional, default value: 0).
Boolean) if true, the room is a game room
(optional, default value: false).
Boolean) if true and in case of game room,
the new room is joined after creation
(optional, default value: true).
Boolean) if true and in case of game room,
allows to join the new room as spectator
(optional, default value: false).
Boolean) if true, the new room will receive the
SFSEvent.onUserCountChange notifications
(optional, default recommended value: false).
Map<String, RoomVariableRequest>) a Map of Room Variables,
as described in the setRoomVariables(java.util.Map) method documentation
(optional, default: none).
String) the name used to reference the extension
(see the SmartFoxServer server-side configuration).
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.SFSEvent.onRoomAdded,
SFSEvent.onCreateRoomError,
SFSEvent.onUserCountChangepublic java.util.Map<java.lang.Integer,Room> getAllRooms()
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());
}
getRoomList(),
Roompublic Buddy getBuddyByName(java.lang.String buddyName)
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));
}
buddyName - the username of the buddy.
buddyList,
getBuddyById(int)public Buddy getBuddyById(int id)
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));
}
id - the user id of the buddy.
buddyList,
getBuddyByName(java.lang.String)public void getBuddyRoom(Buddy buddy)
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);
buddy - a buddy object taken from the buddyList.buddyList,
SFSEvent.onBuddyRoompublic Room getRoom(int roomId)
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());
roomId - the id of the room.
Room object.getRoomByName(java.lang.String),
getAllRooms(),
getRoomList(),
Roompublic Room getRoomByName(java.lang.String roomName)
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());
roomName - the name of the room.
Room object.getRoom(int),
getAllRooms(),
getRoomList(),
Roompublic void getRoomList()
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();
getRoom(int),
getRoomByName(java.lang.String),
getAllRooms(),
SFSEvent.onRoomListUpdatepublic Room getActiveRoom()
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());
Room object of the currently active room;
if the user joined more than one room, the last joined room is returned.activeRoomIdpublic void getRandomKey()
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();
SFSEvent.onRandomKeypublic java.lang.String getUploadPath()
The following example shows how to get the default upload path.
String path = smartFox.getUploadPath();
public java.lang.String getVersion()
The following example shows how to display the SmartFoxServer API version.
System.out.println("Current API version: " + smartFox.getVersion());
public void joinRoom(int newRoom)
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);
SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError
public void joinRoom(int newRoom,
java.lang.String pword,
boolean dontLeave)
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);
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.SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError
public void joinRoom(int newRoom,
java.lang.String pword,
boolean isSpectator,
boolean dontLeave)
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);
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.SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError
public void joinRoom(int newRoom,
java.lang.String pword,
boolean isSpectator,
boolean dontLeave,
int oldRoom)
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);
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.SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError
public void joinRoom(java.lang.String newRoom,
java.lang.String pword,
boolean dontLeave)
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);
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.SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError
public void joinRoom(java.lang.String newRoom,
java.lang.String pword,
boolean isSpectator,
boolean dontLeave)
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);
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.SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomError
public void joinRoom(java.lang.String newRoom,
java.lang.String pword,
boolean isSpectator,
boolean dontLeave,
int oldRoom)
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);
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.SFSEvent.onJoinRoom,
SFSEvent.onJoinRoomErrorpublic void leaveRoom(int roomId)
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);
roomId - the id of the room to leave.joinRoom(int),
SFSEvent.onRoomLeftpublic void loadBuddyList()
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();
buddyList,
SFSEvent.onBuddyList,
SFSEvent.onBuddyListError
public void login(java.lang.String zone,
java.lang.String name,
java.lang.String pass)
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", "");
zone - the name of the zone to log into.name - the user name.pass - the user password. Empty String if no password.logout(),
SFSEvent.onLoginpublic void logout()
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();
login(java.lang.String, java.lang.String, java.lang.String),
SFSEvent.onLogoutpublic void removeBuddy(java.lang.String buddyName)
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.
<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);
buddyName - the name of the user to be removed from the buddy list.buddyList,
addBuddy(java.lang.String),
SFSEvent.onBuddyListpublic void roundTripBench()
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();
SFSEvent.onRoundTripResponse
public void sendBuddyPermissionResponse(boolean allowBuddy,
java.lang.String targetBuddy)
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"));
}
});
allowBuddy - true to grant permission,
false to refuse to be added to the requester's buddy list.targetBuddy - the username of the requester.addBuddy(java.lang.String),
SFSEvent.onBuddyPermissionRequestpublic void sendPublicMessage(java.lang.String 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!");
message - the text of the public message.sendPrivateMessage(java.lang.String, int),
SFSEvent.onPublicMessage
public void sendPublicMessage(java.lang.String message,
int roomId)
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);
message - the text of the public message.roomId - the id of the target room, in case of multi-room join.sendPrivateMessage(java.lang.String, int),
SFSEvent.onPublicMessage
public void sendPrivateMessage(java.lang.String message,
int recipientId)
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!");
message - the text of the private message.recipientId - the id of the recipient user.sendPublicMessage(java.lang.String),
SFSEvent.onPrivateMessage
public void sendPrivateMessage(java.lang.String message,
int recipientId,
int roomId)
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);
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.sendPublicMessage(java.lang.String),
SFSEvent.onPrivateMessage
public void sendModeratorMessage(java.lang.String message,
java.lang.String type,
int id)
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).
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).login(java.lang.String, java.lang.String, java.lang.String),
MODMSG_TO_USER,
MODMSG_TO_ROOM,
MODMSG_TO_ZONE,
SFSEvent.onModeratorMessagepublic void sendObject(SFSObject obj)
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);
obj - the object to be sent. Supported classes are: Boolean, Double, String, SFSObject.sendObjectToGroup(it.gotoandplay.smartfoxclient.data.SFSObject, int[]),
SFSEvent.onObjectReceived
public void sendObject(SFSObject obj,
int roomId)
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);
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.sendObjectToGroup(it.gotoandplay.smartfoxclient.data.SFSObject, int[]),
SFSEvent.onObjectReceived
public void sendObjectToGroup(SFSObject obj,
int[] userList)
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});
obj - the object to be sent. Supported classes are: Boolean, Double, String, SFSObject.userList - an array containing the id(s) of the recipients.sendObject(it.gotoandplay.smartfoxclient.data.SFSObject),
SFSEvent.onObjectReceived
public void sendObjectToGroup(SFSObject obj,
int[] userList,
int roomId)
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);
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.sendObject(it.gotoandplay.smartfoxclient.data.SFSObject),
SFSEvent.onObjectReceived
public void sendXtMessage(java.lang.String xtName,
java.lang.String cmd,
SFSObject paramObj)
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);
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.XTMSG_TYPE_XML,
SFSEvent.onExtensionResponse
public void sendXtMessage(java.lang.String xtName,
java.lang.String cmd,
SFSObject paramObj,
int roomId)
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);
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.XTMSG_TYPE_XML,
SFSEvent.onExtensionResponse
public void sendXtMessage(java.lang.String xtName,
java.lang.String cmd,
org.json.JSONObject paramObj)
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();
}
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).XTMSG_TYPE_JSON,
SFSEvent.onExtensionResponse
public void sendXtMessage(java.lang.String xtName,
java.lang.String cmd,
org.json.JSONObject paramObj,
int roomId)
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();
}
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.XTMSG_TYPE_JSON,
SFSEvent.onExtensionResponse
public void sendXtMessage(java.lang.String xtName,
java.lang.String cmd,
java.lang.String[] params)
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);
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).XTMSG_TYPE_STR,
SFSEvent.onExtensionResponse
public void sendXtMessage(java.lang.String xtName,
java.lang.String cmd,
java.lang.String[] params,
int roomId)
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);
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.XTMSG_TYPE_STR,
SFSEvent.onExtensionResponse
public void setBuddyBlockStatus(java.lang.String buddyName,
boolean status)
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);
buddyName - the name of the buddy to be blocked or unblocked.status - true to block the buddy, false to unblock the buddy.buddyListpublic void setBuddyVariables(java.util.Map<java.lang.String,java.lang.String> varList)
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).
<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);
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.myBuddyVars,
SFSEvent.onBuddyListUpdatepublic void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars)
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());
}
}
});
vars - Map containing the room variables name as key and the room variables as value.Room.getVariable(java.lang.String),
Room.getVariables(),
SFSEvent.onRoomVariablesUpdate
public void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars,
int roomId)
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());
}
}
});
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.Room.getVariable(java.lang.String),
Room.getVariables(),
SFSEvent.onRoomVariablesUpdate
public void setRoomVariables(java.util.Map<java.lang.String,RoomVariableRequest> vars,
int roomId,
boolean setOwnership)
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);
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.Room.getVariable(java.lang.String),
Room.getVariables(),
SFSEvent.onRoomVariablesUpdatepublic void setUserVariables(java.util.Map<java.lang.String,SFSVariable> vars)
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);
vars - Map containing the user variables name as key and the room variables as value.User.getVariable(java.lang.String),
User.getVariables(),
SFSEvent.onUserVariablesUpdate
public void setUserVariables(java.util.Map<java.lang.String,SFSVariable> vars,
int roomId)
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);
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.User.getVariable(java.lang.String),
User.getVariables(),
SFSEvent.onUserVariablesUpdatepublic void switchSpectator()
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();
User.isSpectator(),
SFSEvent.onSpectatorSwitchedpublic void switchSpectator(int roomId)
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);
}
});
roomId - the id of the room where the spectator should be switched, in case of molti-room join.User.isSpectator(),
SFSEvent.onSpectatorSwitchedpublic void switchPlayer()
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();
}
});
switchPlayer(int),
User.isSpectator(),
SFSEvent.onPlayerSwitchedpublic void switchPlayer(int roomId)
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);
}
});
roomId - the id of the room where the player should be switched
to spectator.User.isSpectator(),
SFSEvent.onPlayerSwitchedpublic void __logout()
public void sendString(java.lang.String strMessage)
public void sendJson(java.lang.String jsMessage)
public long getBenchStartTime()
public void clearRoomList()
public void handleEvent(SFSEvent event)
ISFSEventListener
handleEvent in interface ISFSEventListenerevent - the event that is fired.public void onConnect(boolean success)
onConnect in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandlerpublic void onClose()
onClose in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandlerpublic void onError(java.lang.Exception e)
onError in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandlerpublic void onData(java.lang.String message)
onData in interface it.gotoandplay.utils.net.xmlsocket.IXMLSocketEventHandler
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||