Class SmartFox
- All Implemented Interfaces:
sfs3.client.core.IDispatchable,ISmartFox
NOTE: in all the examples in this documentation, sfs always refers to a SmartFox instance.
Example of usage:
import sfs3.client.*;
import sfs3.client.requests.*;
import sfs3.client.util.ConfigData;
public class SFS3Connector
{
SmartFox sfs;
ConfigData cfg;
public SFS3Connector()
{
// Configure client connection settings
cfg = new ConfigData();
cfg.host = "localhost";
cfg.zone = "Playground";
// Set up event handlers
sfs = new SmartFox();
sfs.addEventListener(SFSEvent.CONNECTION, this::onConnection);
sfs.addEventListener(SFSEvent.CONNECTION_LOST, this::onConnectionLost);
sfs.addEventListener(SFSEvent.LOGIN, this::onLogin);
sfs.addEventListener(SFSEvent.LOGIN_ERROR, this::onLoginError);
System.out.println("API Ver: " + sfs.getVersion());
// Connect to the server
sfs.connect(cfg);
}
// ----------------------------------------------------------------------
// Event Handlers
// ----------------------------------------------------------------------
private void onConnection(ApiEvent evt)
{
var success = (Boolean) evt.getParam(EventParam.Success);
if (success)
{
System.out.println("Connection success");
// Login as guest: the user name will be auto-assigned by the server
sfs.send(new LoginRequest(""));
}
else
System.out.println("Connection Failed. Is the server running?");
}
private void onConnectionLost(ApiEvent evt)
{
System.out.println("Connection was lost");
}
private void onLogin(ApiEvent evt)
{
var me = (User) evt.getParam(EventParam.User);
System.out.println("Logged in as: " + me.getName());
}
private void onLoginError(ApiEvent evt)
{
var message = (String) evt.getParam(EventParam.ErrorMessage);
System.out.println("Login failed. Error: " + message);
}
}
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected sfs3.client.bitswarm.BitSwarmClientprotected sfs3.client.core.EventDispatcherprotected ExecutorServiceprotected org.slf4j.Loggerprotected ScheduledExecutorService -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddEventListener(String eventType, IEventListener listener) Adds an event listener to handle a specific eventvoidconnect(ConfigData cfgData) Attempts to connect to the server.voidInitializes the UDP protocol by performing an handshake with the server.voidManually disconnect from the server.voidCloses the current UDP Connection.voiddispatchEvent(ApiEvent evt) voidenableLagMonitor(boolean enabled) voidenableLagMonitor(boolean enabled, int interval) voidenableLagMonitor(boolean enabled, int interval, int queueSize) Enables the automatic monitoring of latency between client and the server in a round-robin fashion.sfs3.client.bitswarm.BitSwarmClientReturns a reference to the Buddy Manager.Get the client configuration details.Returns the current connection mode after a connection has been successfully established.sfs3.client.core.EventDispatcherReturns the HTTP/HTTPS URI that can be used to upload files to SmartFoxServer, using an HTTP POST request.Returns a list of Room objects representing the Rooms currently joined by the client.sfs3.client.util.LagMonitorReturns the object representing the last Room joined by the client, if any.Returns the User object representing the client when connected to a SmartFoxServer instance.sfs3.client.util.NetDebugLevelReturns a reference to the Room Manager.This can be used to schedule simple delayed Tasks.Returns the current session token.Returns a reference to the User Manager.Returns the current version of the SmartFoxServer 3 Client API.voidvoidprotected final voidinit()booleanbooleanbooleanvoidUsed to simulate an unexpected connection, to test the reconnection system.voidUsed to clear all listeners previously added.voidremoveEventListener(String eventType, IEventListener listener) Used to remove a single event listeners that was previously addedvoidsend(sfs3.client.requests.IClientRequest request) Sends a request to the server.voidsetClientDetails(String platformId, String version) Allows to specify custom client details that will be used to gather statistics about the client platform via the SmartFox Analytics Module.voidsetExecutor(ExecutorService service) voidsetJoining(boolean value) voidsetLastJoinedRoom(Room lastJoinedRoom) voidvoidvoidsetReconnectionSeconds(int seconds) protected void
-
Field Details
-
log
protected org.slf4j.Logger log -
dispatcher
protected sfs3.client.core.EventDispatcher dispatcher -
eventThreadPool
-
scheduler
-
bitSwarm
protected sfs3.client.bitswarm.BitSwarmClient bitSwarm
-
-
Constructor Details
-
SmartFox
public SmartFox()
-
-
Method Details
-
init
protected final void init() -
getBitSwarm
public sfs3.client.bitswarm.BitSwarmClient getBitSwarm()- Specified by:
getBitSwarmin interfaceISmartFox- Internal
-
getScheduler
This can be used to schedule simple delayed Tasks. In case you're planning to run hundreds of Tasks you should probably create a dedicated ScheduledExecutorService, sized the way you need it.- Specified by:
getSchedulerin interfaceISmartFox- Returns:
- the main scheduler used to schedule tasks
- See Also:
-
getMySelf
Returns the User object representing the client when connected to a SmartFoxServer instance. This object is generated upon successful login, so it isnullbefore the login or if the login request failed. -
setMySelf
-
isJoining
public boolean isJoining()- Internal
-
setJoining
public void setJoining(boolean value) - Specified by:
setJoiningin interfaceISmartFox- Internal
-
getVersion
Returns the current version of the SmartFoxServer 3 Client API. Example
The following example traces the SmartFoxServer API version to the console:System.out.println("Current API version:" + sfs.getVersion());- Specified by:
getVersionin interfaceISmartFox
-
getConfig
Get the client configuration details. -
getSessionToken
Returns the current session token. The Session token is a unique string sent by the server to the client after the initial handshake.- Specified by:
getSessionTokenin interfaceISmartFox- Returns:
- the current session token
-
getLastJoinedRoom
Returns the object representing the last Room joined by the client, if any. This property isnullif no Room has been joined, yet. You can use the JoinRoomRequest request to join a Room.- Specified by:
getLastJoinedRoomin interfaceISmartFox- Returns:
- the last joined Room
- See Also:
-
setLastJoinedRoom
- Specified by:
setLastJoinedRoomin interfaceISmartFox- Internal
-
getJoinedRooms
Returns a list of Room objects representing the Rooms currently joined by the client.NOTE: the same list is returned by the IRoomManager.getJoinedRooms() method, accessible through the roomManager getter
- Specified by:
getJoinedRoomsin interfaceISmartFox- Returns:
- the list of joined Rooms
- See Also:
-
getUserManager
Returns a reference to the User Manager. This manager is used internally by the SmartFoxServer API; the reference returned by this method gives access to the user list.- Specified by:
getUserManagerin interfaceISmartFox- Returns:
- the User Manager
-
getRoomManager
Returns a reference to the Room Manager. This manager is used internally by the SmartFoxServer API; the reference returned by this method gives access to the Rooms list and Groups.- Specified by:
getRoomManagerin interfaceISmartFox- Returns:
- the Room Manager
-
getBuddyManager
Returns a reference to the Buddy Manager. This manager is used internally by the SmartFoxServer API; the reference returned by this method gives access to the buddy list and relative buddy variables.- Specified by:
getBuddyManagerin interfaceISmartFox- Returns:
- the Buddy Manager
- See Also:
-
getConnectionMode
Returns the current connection mode after a connection has been successfully established. Possible values are defined as constants in the ConnectionMode class. Example
The following example traces the current connection mode:System.out.println("Connection mode: " + sfs.getConnectionMode());- Specified by:
getConnectionModein interfaceISmartFox- See Also:
-
getHttpUploadURI
Returns the HTTP/HTTPS URI that can be used to upload files to SmartFoxServer, using an HTTP POST request. For more info on client side uploads see the relative tutorial in the online documentation under Advanced Topics > File Uploads- Returns:
- the HTTP/HTTPS URI to upload files via a POST request.
-
getExecutor
- Specified by:
getExecutorin interfaceISmartFox- Internal
-
setExecutor
- Specified by:
setExecutorin interfaceISmartFox- Internal
-
setReconnectionSeconds
public void setReconnectionSeconds(int seconds) - Specified by:
setReconnectionSecondsin interfaceISmartFox- Internal
-
setClientDetails
Allows to specify custom client details that will be used to gather statistics about the client platform via the SmartFox Analytics Module. By default the generic "Java/Android" label is used as platform, without specifying the version.
This method must be called before the connection is started.
The length of the two strings combined must be < 512 characters.- Specified by:
setClientDetailsin interfaceISmartFox- Parameters:
platformId- the id of the platform (e.g. Java, Android etc...)version- the version of the platform
-
getNetDebugLevel
public sfs3.client.util.NetDebugLevel getNetDebugLevel()- Specified by:
getNetDebugLevelin interfaceISmartFox
-
addEventListener
Adds an event listener to handle a specific eventExample:
var sfs = new SmartFox(); sfs.addEventListener(SFSEvent.CONNECTION, this::onConnection); // ... var cfgData = new ConfigData(); sfs.connect(cfgData); private void onConnection(ApiEvent evt) { var success = (Boolean) evt.getParam(EventParam.Success); if (success) { log.info("Connection success: " + sfs.getConfig().host + ", mode: " + sfs.getConnectionMode()); sfs.send(new LoginRequest(""); } else { var errMsg = evt.getParam(EventParam.ErrorMessage); log.warn("Connection Failed: " + errMsg); } }- Specified by:
addEventListenerin interfaceISmartFox- Parameters:
eventType- the event namelistener- the listener responding to the event- See Also:
-
removeEventListener
Used to remove a single event listeners that was previously added- Specified by:
removeEventListenerin interfaceISmartFox- Parameters:
eventType- the event namelistener- the previous listener that was added- See Also:
-
removeAllEventListeners
public void removeAllEventListeners()Used to clear all listeners previously added. Useful after a disconnection to remove all listeners at once.- Specified by:
removeAllEventListenersin interfaceISmartFox
-
getDispatcher
public sfs3.client.core.EventDispatcher getDispatcher()- Specified by:
getDispatcherin interfacesfs3.client.core.IDispatchable- Internal
-
dispatchEvent
- Specified by:
dispatchEventin interfaceISmartFox- Internal
-
isConnected
public boolean isConnected()- Specified by:
isConnectedin interfaceISmartFox- Returns:
- true if we have an active TCP connection to the server, false otherwise
-
isUdpConnected
public boolean isUdpConnected()- Specified by:
isUdpConnectedin interfaceISmartFox- Returns:
- true if we have an active UDP connection to the server, false otherwise
-
connect
Attempts to connect to the server. Triggers anSFSEvent.CONNECTIONevent -
disconnect
public void disconnect()Manually disconnect from the server. Triggers anSFSEvent.CONNECTION_LOSTevent- Specified by:
disconnectin interfaceISmartFox
-
killConnection
public void killConnection()Used to simulate an unexpected connection, to test the reconnection system. For more information see the online SmartFoxServer3 documentation under Development Basics > Reconnection system- Specified by:
killConnectionin interfaceISmartFox
-
getNodeId
-
setNodeId
-
connectUdp
public void connectUdp()Initializes the UDP protocol by performing an handshake with the server. Triggers aSFSEvent.UDP_CONNECTIONevent.This method can be called at any time, provided that a TCP connection to the server has already been established. After a successful initialization, UDP requests can be sent to a server-side Extension at any time.
For more information and examples see the SFS3 Documentation under Advanced Topics > Using the UDP Protocol- Specified by:
connectUdpin interfaceISmartFox
-
disconnectUdp
public void disconnectUdp()Closes the current UDP Connection. Triggers aSFSEvent.UDP_CONNECTION_LOSTevent.- Specified by:
disconnectUdpin interfaceISmartFox
-
send
public void send(sfs3.client.requests.IClientRequest request) Sends a request to the server. All the available request objects can be found in the requests package. -
enableLagMonitor
public void enableLagMonitor(boolean enabled, int interval, int queueSize) Enables the automatic monitoring of latency between client and the server in a round-robin fashion. When turned on, theSFSEvent.PING_PONGevent type is dispatched continuously, providing the average of the last 10 measured lag values, plus the highest and lowest values recorded.NOTE: the lag monitoring can be enabled after having logged in successfully.
- Parameters:
enabled- The lag monitoring status:trueto start the monitoring,falseto stop it.interval- An optional amount of seconds to pause between each query (recommended 3-4s)queueSize- The amount of values stored temporarily and used to calculate the average lag- See Also:
-
enableLagMonitor
public void enableLagMonitor(boolean enabled) - See Also:
-
enableLagMonitor
public void enableLagMonitor(boolean enabled, int interval) - See Also:
-
getLagMonitor
public sfs3.client.util.LagMonitor getLagMonitor()- Specified by:
getLagMonitorin interfaceISmartFox- Internal
-
handleLogout
public void handleLogout()- Specified by:
handleLogoutin interfaceISmartFox- Internal
-
stopExecutors
protected void stopExecutors() -
handleHandShake
- Specified by:
handleHandShakein interfaceISmartFox- Internal
-