SFS2X Objective-C API  1.7.13
iOS / macOS / tvOS
SmartFox2XClient Class Reference

#import <SmartFox2XClient.h>

Inherits NSObject, <IBitSwarmEvents>, and <IConfigLoader>.

Instance Methods

(void) - handleHandshake:
 
(void) - setReconnectionSeconds:
 
(NSInteger) - getReconnectionSeconds
 
(void) - handleClientDisconnection:
 
(void) - handleReconnectionFailure
 
(void) - handleLogout
 
(void) - handleLogin:
 
(BitSwarmClient *) - getSocketEngine
 
(id) - initSmartFoxWithDebugMode:delegate:
 
(void) - connect
 
(void) - connect:port:
 
(void) - connectWithConfig:
 
(void) - disconnect
 
(void) - killConnection
 
(void) - enableLagMonitor:
 
(void) - enableLagMonitorWithInterval:interval:queueSize:
 
(NSString *) - httpUploadURI
 
(void) - loadConfig:connectOnSuccess:
 
(void) - loadConfig
 
(void) - send:
 
(id< Room >) - getRoomById:
 
(id< Room >) - getRoomByName:
 
(NSArray *) - getRoomListFromGroup:
 
(void) - initUDP:udpHost:
 
(void) - setClientDetails:platformId:
 
(void) - initCrypto
 
(NSRunLoopMode) - getRunLoopMode
 
(void) - setRunLoopMode:
 

Class Methods

(id) + smartFoxWithDebugMode:delegate:
 

Properties

id< IBuddyManager > buddyManager
 
NSInteger compressionThreshold
 
ConfigDataconfig
 
NSString * currentIp
 
NSInteger currentPort
 
NSString * currentZone
 
BOOL debug
 
BOOL useBlueBox
 
BOOL isConnected
 
NSString * connectionMode
 
LagMonitor * lagMonitor
 
NSMutableArray * joinedRooms
 
id< Room > lastJoinedRoom
 
Logger * logger
 
id< User > mySelf
 
NSArray * roomList
 
id< IRoomManager > roomManager
 
NSString * sessionToken
 
id< IUserManager > userManager
 
NSString * version
 
BitSwarmClient * bitSwarm
 
BOOL isJoining
 
id< ISFSEventsdelegate
 

Detailed Description

SmartFox2XClient is the main class in the SFS2X API.

This class is responsible for connecting to the Server and dispatching all asynchronous events.

Warning
*Important:* in the provided examples, smartFox always indicates a SmartFox2XClient instance.

Method Documentation

◆ connect

- (void) connect

Establish connection with SmartFoxServer 2X.

Client will use the settings loaded via loadConfig

Exceptions
NSExceptionif host/address or port in the config file is invalid.
See also
- loadConfig:connectOnSuccess:

◆ connect:port:

- (void) connect: (NSString *)  host
port: (int)  port 

Establish connection with SmartFoxServer 2X.

Client will use the settings loaded via loadConfig if you pass nil value for host or -1 for port.

Parameters
host(NSString *) the address of the server to connect to
port(NSInteger) the TCP port (default port used by SFS2X is 9933)
Exceptions
NSExceptionif an invalid host/address or port is passed
See also
- connect
- loadConfig:connectOnSuccess:

◆ connectWithConfig:

- (void) connectWithConfig: (ConfigData *)  cfg

Establish connection with SmartFoxServer 2X using a defined Configuration Object

Client will use the settings loaded via loadConfig if you pass nil value for host or -1 for port.

Parameters
cfg(ConfigData *) configuration paramaters (host, port, etc)
Exceptions
NSExceptionif an invalid host/address or port is passed

Example:
The following example shows how to pass a ConfigData object to connect directly with SFS 2X.

smartFox = [[SmartFox2XClient alloc] initSmartFoxWithDebugMode:YES delegate:self];
ConfigData *cfg = [[ConfigData alloc] init];
cfg.host = @"127.0.0.1";
cfg.port = 9933;
cfg.zone = @"BasicExamples";
cfg.useBlueBox = YES;
// Start connection
[smartFox connectWithConfig:cfg];
// Handle connection event
-(void) onConnection:(SFSEvent *)evt
{
NSNumber *success = [evt.params objectForKey:@"success"];
if (success)
{
NSLog(@"Connection success");
}
else
{
NSLog(@"Connection failure");
}
}
See also
ConfigData

◆ disconnect

- (void) disconnect

Disconnect from SmartFoxServer.

◆ enableLagMonitor:

- (void) enableLagMonitor: (BOOL)  enabled

Enable the lag monitor.

Toggles the automatic realtime monitoring of the lag between the client and the server (round robin). When turned on, the ISFSEvent.onPingPong event is called every 4 seconds, providing the average of the last ten measured lag values.

The Lag Monitor can be activated after the client has successfully logged in the Server. The monitoring is automatically turned off when the user logs out of a Zone or gets disconnected.

Parameters
enabled(BOOL) toggles the state of the Lag Monitor

◆ enableLagMonitorWithInterval:interval:queueSize:

- (void) enableLagMonitorWithInterval: (BOOL)  enabled
interval: (NSInteger)  interval
queueSize: (NSInteger)  qSize 

Enable the lag monitor with custom settings

Toggles the automatic realtime monitoring of the lag between the client and the server (round robin) with custom settings.

The Lag Monitor can be activated after the client has successfully logged in the Server. The monitoring is automatically turned off when the user logs out of a Zone or gets disconnected.

Parameters
enabled(BOOL) toggles the state of the Lag Monitor
interval(NSInteger) the number of seconds between each roundtrip calls (default = 4)
qSize(NSInteger) the number of measuerments kept in the local queue upon which the average is calculated (default = 10)

◆ getRoomById:

- (id< Room >) getRoomById: (NSInteger)  roomId

Finds a Room from its Id or returns nil if no Room with that Id exist in the room list

Parameters
roomId(NSInteger) the id of the room.
See also
roomList
SFSRoom

◆ getRoomByName:

- (id< Room >) getRoomByName: (NSString *)  roomName

Finds a Room from its name or returns nil if no Room with that name exist in the room list

Parameters
roomName(NSString *) the name of the room.
See also
roomList
SFSRoom

◆ getRoomListFromGroup:

- (NSArray *) getRoomListFromGroup: (NSString *)  groupId

Return the list of Rooms from a specific Room Group

Parameters
groupId(NSString *)the name of the Group
Returns
the list of rooms
See also
SFSRoom

◆ getRunLoopMode

- (NSRunLoopMode) getRunLoopMode

Returns the current run loop mode. Unless specified otherwise NSDefaultRunLoopMode is used by default.

To learn more about run loop modes please refer to Apple's official documentation. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html

◆ httpUploadURI

- (NSString *) httpUploadURI

Returns the HTTP URI that can be used to upload files to, using regular HTTP POST. For more details on how to use this functionality see the Upload File tutorial

NOTE: this property will return null if no API configuration has been set or the local User is not already logged in the server.

◆ initCrypto

- (void) initCrypto

Initializes the connection cryptography. Once this process is successfully completed all of the server's data will be encrypted using standard AES 128-bit algorithm, using a secure key served over HTTPS.

NOTE: It is necessary to send this request right after a successful connection event, before login.

Example:
The code below allows to easily toggle the use of encryption for local vs production testing.

BOOL useEncryption = YES;
smartFox = [[SmartFox2XClient alloc] initSmartFoxWithDebugMode:YES delegate:self];
ConfigData *cfg = [[ConfigData alloc] init];
cfg.host = @"127.0.0.1";
cfg.port = 9933;
cfg.zone = @"BasicExamples";
// Start connection
[smartFox connectWithConfig:cfg];
-(void) onConnection:(SFSEvent *)evt
{
NSNumber *success = [evt.params objectForKey:@"success"];
if (success)
{
if (useEncryption)
[smartFox initCrypto];
else
[self sendLogin];
}
else
NSLog(@"Connection failed");
}
- (void)onCryptoInit:(SFSEvent *)evt
{
NSNumber* success = [evt.params objectForKey:@"success"];
if (success)
{
NSLog(@"Crypto Init Success!");
[self sendLogin];
}
else
NSLog(@"Crypto Init Failure!");
}
-(void) sendLogin
{
[smartFox send:[LoginRequest requestWithUserName:@"" password:@"" zoneName:smartFox.config.zone params:nil]];
}
-(void) onLogin:(SFSEvent *)evt
{
NSLog("Logged in as: %@", smartFox.mySelf.name];
}

◆ initSmartFoxWithDebugMode:delegate:

- (id) initSmartFoxWithDebugMode: (BOOL)  debug
delegate: (id <ISFSEvents>)  delegate 

Initializes SmartFox Client

Parameters
debug(BOOL) determines debugging mode.
delegate(id <ISFSEvents>) delegate object that listens api events.
See also
+ smartFoxWithDebugMode:delegate:

◆ initUDP:udpHost:

- (void) initUDP: (NSString *) 
udpHost: (NSInteger)  udpPort 

Initialize the UDP Manager to create a UDP connection. If the host and port parameters are left nil and -1

The UDP Manager will use the settings found in the config XML. UDP is only available through an ExtensionRequest.

Parameters
udpHost(NSString *) the host (IP) of the SFS Server
udpPort(NSInteger) the port of the SFS Server to handle UDP
-(void)onLogin:(SFSEvent *)evt
{
NSArray *keys = [evt.params allKeys];
for (NSString *key in keys)
{
// do somthing...
}
//initialize the UDP socket
[smartFox initUDP :nil :-1];
}

Important: It is recommended to initialize the UDP connection after successful login to a zone.

◆ killConnection

- (void) killConnection

Simulate an abrupt disconnection

To be used for testing/simulations only.

◆ loadConfig:connectOnSuccess:

- (void) loadConfig: (NSString *)  filePath
connectOnSuccess: (BOOL)  connectOnSuccess 

Load a client configuration file.

The SmartFox2XClient instance can be configured through an external xml configuration file loaded at run-time. By default, the loadConfig method loads a file named sfs—config.xml, placed in the main bundle of the application. If the connectOnSuccess parameter is set to YES, on loading completion the connect:port: method is automatically called by the API, otherwise the onConfigLoadSuccess event is dispatched. In case of a loading error, the onConfigLoadFailure (ISFSEvents) event is fired.

Parameters
filePath(NSString *) external xml configuration file name (optional).
connectOnSuccess(BOOL) a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.

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

<SmartFoxConfig>
<ip>127.0.0.1</ip>
<port>9933</port>
<udpHost>127.0.0.1</udpHost>
<udpPort>9934</udpPort>
<zone>BasicExamples</zone>
<debug>true</debug>
<httpPort>8080</httpPort>
<blueBoxPollingRate>750</blueBoxPollingRate>
</SmartFoxConfig>

Example:

The following example shows how to load an external configuration file.
[smartfox loadConfig:@"sfs-config.xml" connectOnSuccess:NO];
-(void)onConfigLoadSuccess:(SFSEvent *)evt
{
NSLog(@"Config file loaded, now connecting...");
[smartFox connect:smartFox.ipAddress, smartFox.port];
}
-(void)onConfigLoadFailure:(SFSEvent *)evt
{
NSLog(@"Failed loading config file: %@", [evt.params objectForKey:@"message"]);
}
See also
[ISFSEvents onConfigLoadSuccess:]
[ISFSEvents onConfigLoadFailure:]
Warning
*Important:* The SmartFox2XClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).

◆ send:

- (void) send: (id <IRequest>)  request

Sends a request to the Server.

All the available request objects are found in the documentation.

Parameters
request(id <IRequest>) a request object.

Example:

[smartFox send:[LoginRequest requestWithUserName:@"" password:@"" zoneName:smartFox.config.zone params:nil]];

◆ setClientDetails:platformId:

- (void) setClientDetails: (NSString *) 
platformId: (NSString *)  version 

Allows to specify custom client details what will be used to gather statistics about the client platform via the Analytics Module. By default no details are sent.

This method must be called before the connection is started. The length of the two strings combined must be < 512 characters.

Parameters
platformId(NSString *) The id of the runtime platform: for example "Unity WebPlayer" or "iOS".
version(NSString *) An optional version of the runtime platform: for example "2.0.0".

Example

[smartFox setClientDetails:@"MyPlatform" :@"version 001"];

◆ setRunLoopMode:

- (void) setRunLoopMode: (NSRunLoopMode)  mode

Allows to choose between two run loop modes

The default mode is NSDefaultRunLoopMode. The alternative mode is NSRunLoopCommonModes. The latter can be useful to use in conjunction with UI widgets such as UIViewTable that don't allow event dispatching while scrolling.

IMPORTANT: make sure to change the run loop mode only before starting a connection.

To learn more about run loop modes please refer to Apple's official documentation. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html

Parameters
mode(NSRunLoopMode) the run loop mode

Example:

_sfs = [[SmartFox2XClient alloc] initSmartFoxWithDebugMode:YES delegate:self];
// Switch to different run loop mode
[[_sfs getSocketEngine] setRunLoopMode:NSRunLoopCommonModes];
// Connection code...

◆ smartFoxWithDebugMode:delegate:

+ (id) smartFoxWithDebugMode: (BOOL)  debug
delegate: (id <ISFSEvents>)  delegate 

Initializes and returns SmartFox2XClient instance.

Parameters
debug(BOOL) determines debugging mode.
delegate(id <ISFSEvents>) delegate object that listens api events.
See also
- initSmartFoxWithDebugMode:delegate:

Property Documentation

◆ buddyManager

- (id<IBuddyManager>) buddyManager
readwriteatomicstrong

Returns the Buddy Manager.

See also
SFSBuddyManager

◆ compressionThreshold

- (NSInteger) compressionThreshold
readatomicassign

Returns the current compression threshold.

The value represent the maximum message size (in bytes) before the protocol compression is activated. The value is determined by the server configuration.

◆ config

- (ConfigData*) config
readwriteatomicstrong

Get the current client configuration.

It can return null if the configuration was not loaded.

See also
- loadConfig:connectOnSuccess:

◆ connectionMode

- (NSString *) connectionMode
readatomicweak

Returns the mode of the connection (Socket or HTTP)

◆ currentIp

- (NSString *) currentIp
readatomicweak

The address where the client is connected (if the client is connected)

See also
- connect:port:
- loadConfig:connectOnSuccess:

◆ currentPort

- (NSInteger) currentPort
readatomicassign

The TCP port of the server where the client is connected (if the client is connected)

See also
- loadConfig:connectOnSuccess:
LoginRequest

◆ currentZone

- (NSString*) currentZone
readwriteatomicstrong

The current Zone in use, if user is logged in

See also
- loadConfig:connectOnSuccess:
LoginRequest

◆ debug

- (BOOL) debug
readwriteatomicassign

When set to true, provides detailed debugging data for all incoming/outgoing messages

◆ isConnected

- (BOOL) isConnected
readatomicassign

Returns true if the client connection is active

◆ joinedRooms

- (NSMutableArray *) joinedRooms
readatomicweak

Returns a list of Rooms currently joined by the client

See also
JoinRoomRequest

◆ lastJoinedRoom

- (id<Room>) lastJoinedRoom
readwriteatomicstrong

Return the last joined Room, if any.

Null is returned if there's no currently joined Room.

See also
JoinRoomRequest

◆ logger

- (Logger*) logger
readatomicweak

Get a reference to the logger

Returns
the logger

◆ mySelf

- (id<User>) mySelf
readwriteatomicstrong

This User object represents the User connected to SmartFoxServer 2X

See also
LoginRequest

◆ roomList

- (NSArray *) roomList
readatomicweak

Returns the list of Rooms currently "watched" by the client.

The list will contain all the Rooms that are currently joined and all the Rooms from the Room Groups that are subscribed. At login time the User is automatically subscribed to all Room Groups specified in the Zone's Default Groups setting.

See also
SubscribeRoomGroupRequest
UnsubscribeRoomGroupRequest

◆ roomManager

- (id<IRoomManager>) roomManager
readwriteatomicstrong

Returns the Room Manager.

See also
SFSRoomManager

◆ sessionToken

- (NSString*) sessionToken
readwriteatomicstrong

Returns the unique session token.

The Session token is a String sent by the server to the client after the initial handshake.

◆ useBlueBox

- (BOOL) useBlueBox
readwriteatomicassign

Returns true if the client connection is http tunnelled

◆ userManager

- (id<IUserManager>) userManager
readwriteatomicstrong

Returns the User Manager.

See also
SFSUserManager

◆ version

- (NSString *) version
readatomicweak

Return the API current version

ConfigData
Definition: ConfigData.h:15
SmartFox2XClient::debug
BOOL debug
Definition: SmartFox2XClient.h:227
SmartFox2XClient::useBlueBox
BOOL useBlueBox
Definition: SmartFox2XClient.h:231
LoginRequest
Definition: LoginRequest.h:30
-[SmartFox2XClient connect]
void connect()
Definition: SmartFox2XClient.m:509
SmartFox2XClient
Definition: SmartFox2XClient.h:113
-[SmartFox2XClient initCrypto]
void initCrypto()
Definition: SmartFox2XClient.m:310
SFSEvent
Definition: SFSEvent.h:65