Package sfs3.client

Class SmartFox

java.lang.Object
sfs3.client.SmartFox
All Implemented Interfaces:
sfs3.client.core.IDispatchable, ISmartFox

public class SmartFox extends Object implements ISmartFox, sfs3.client.core.IDispatchable
The main class of the SmartFoxServer 3 API: it is responsible for connecting the client to a SmartFoxServer instance and dispatching all asynchronous events. Developers always interact with the remote server via this object.

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 Details

    • log

      protected org.slf4j.Logger log
    • dispatcher

      protected sfs3.client.core.EventDispatcher dispatcher
    • eventThreadPool

      protected ExecutorService eventThreadPool
    • scheduler

      protected ScheduledExecutorService 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:
      getBitSwarm in interface ISmartFox
      Internal
    • getScheduler

      public ScheduledExecutorService 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:
      getScheduler in interface ISmartFox
      Returns:
      the main scheduler used to schedule tasks
      See Also:
    • getMySelf

      public User getMySelf()
      Returns the User object representing the client when connected to a SmartFoxServer instance. This object is generated upon successful login, so it is null before the login or if the login request failed.

      Specified by:
      getMySelf in interface ISmartFox
      See Also:
    • setMySelf

      public void setMySelf(User mySelf)
      Specified by:
      setMySelf in interface ISmartFox
      Internal
    • isJoining

      public boolean isJoining()
      Internal
    • setJoining

      public void setJoining(boolean value)
      Specified by:
      setJoining in interface ISmartFox
      Internal
    • getVersion

      public String 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:
      getVersion in interface ISmartFox
    • getConfig

      public ConfigData getConfig()
      Get the client configuration details.
      Specified by:
      getConfig in interface ISmartFox
      Returns:
      the client configuration details.
      See Also:
    • getSessionToken

      public String 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:
      getSessionToken in interface ISmartFox
      Returns:
      the current session token
    • getLastJoinedRoom

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

      You can use the JoinRoomRequest request to join a Room.

      Specified by:
      getLastJoinedRoom in interface ISmartFox
      Returns:
      the last joined Room
      See Also:
    • setLastJoinedRoom

      public void setLastJoinedRoom(Room lastJoinedRoom)
      Specified by:
      setLastJoinedRoom in interface ISmartFox
      Internal
    • getJoinedRooms

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

      NOTE: the same list is returned by the IRoomManager.getJoinedRooms() method, accessible through the roomManager getter

      Specified by:
      getJoinedRooms in interface ISmartFox
      Returns:
      the list of joined Rooms
      See Also:
    • getUserManager

      public IUserManager 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:
      getUserManager in interface ISmartFox
      Returns:
      the User Manager
    • getRoomManager

      public IRoomManager 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:
      getRoomManager in interface ISmartFox
      Returns:
      the Room Manager
    • getBuddyManager

      public IBuddyManager 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:
      getBuddyManager in interface ISmartFox
      Returns:
      the Buddy Manager
      See Also:
    • getConnectionMode

      public String 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:
      getConnectionMode in interface ISmartFox
      See Also:
      • ConnectionMode
    • getHttpUploadURI

      public String 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

      public ExecutorService getExecutor()
      Specified by:
      getExecutor in interface ISmartFox
      Internal
    • setExecutor

      public void setExecutor(ExecutorService service)
      Specified by:
      setExecutor in interface ISmartFox
      Internal
    • setReconnectionSeconds

      public void setReconnectionSeconds(int seconds)
      Specified by:
      setReconnectionSeconds in interface ISmartFox
      Internal
    • setClientDetails

      public void setClientDetails(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. 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:
      setClientDetails in interface ISmartFox
      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:
      getNetDebugLevel in interface ISmartFox
    • addEventListener

      public void addEventListener(String eventType, IEventListener listener)
      Adds an event listener to handle a specific event

      Example:

       
       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:
      addEventListener in interface ISmartFox
      Parameters:
      eventType - the event name
      listener - the listener responding to the event
      See Also:
    • removeEventListener

      public void removeEventListener(String eventType, IEventListener listener)
      Used to remove a single event listeners that was previously added
      Specified by:
      removeEventListener in interface ISmartFox
      Parameters:
      eventType - the event name
      listener - 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:
      removeAllEventListeners in interface ISmartFox
    • getDispatcher

      public sfs3.client.core.EventDispatcher getDispatcher()
      Specified by:
      getDispatcher in interface sfs3.client.core.IDispatchable
      Internal
    • dispatchEvent

      public void dispatchEvent(ApiEvent evt)
      Specified by:
      dispatchEvent in interface ISmartFox
      Internal
    • isConnected

      public boolean isConnected()
      Specified by:
      isConnected in interface ISmartFox
      Returns:
      true if we have an active TCP connection to the server, false otherwise
    • isUdpConnected

      public boolean isUdpConnected()
      Specified by:
      isUdpConnected in interface ISmartFox
      Returns:
      true if we have an active UDP connection to the server, false otherwise
    • connect

      public void connect(ConfigData cfgData)
      Attempts to connect to the server. Triggers an SFSEvent.CONNECTION event
      Specified by:
      connect in interface ISmartFox
      Parameters:
      cfgData - , the connection configuration
      See Also:
    • disconnect

      public void disconnect()
      Manually disconnect from the server. Triggers an SFSEvent.CONNECTION_LOST event
      Specified by:
      disconnect in interface ISmartFox
    • 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:
      killConnection in interface ISmartFox
    • getNodeId

      public String getNodeId()
      Specified by:
      getNodeId in interface ISmartFox
      Internal
    • setNodeId

      public void setNodeId(String value)
      Specified by:
      setNodeId in interface ISmartFox
      Internal
    • connectUdp

      public void connectUdp()
      Initializes the UDP protocol by performing an handshake with the server. Triggers a SFSEvent.UDP_CONNECTION event.

      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:
      connectUdp in interface ISmartFox
    • disconnectUdp

      public void disconnectUdp()
      Closes the current UDP Connection. Triggers a SFSEvent.UDP_CONNECTION_LOST event.
      Specified by:
      disconnectUdp in interface ISmartFox
    • 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.
      Specified by:
      send in interface ISmartFox
      Parameters:
      request - A request object.
    • 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, the SFSEvent.PING_PONG event 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: true to start the monitoring, false to stop it.
      interval - An optional amount of seconds to pause between each query (recommended 3-4s)
      queueSize - The amount of values stored temporarily and used to calculate the average lag
      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:
      getLagMonitor in interface ISmartFox
      Internal
    • handleLogout

      public void handleLogout()
      Specified by:
      handleLogout in interface ISmartFox
      Internal
    • stopExecutors

      protected void stopExecutors()
    • handleHandShake

      public void handleHandShake(ISFSObject obj)
      Specified by:
      handleHandShake in interface ISmartFox
      Internal