Class: SFSApi

SFSApi

The SFSApi class provides the central access to the main SmartFoxServer 2X server side API. It contains all basic methods for interacting with the server: creating Rooms, joining them, logging in/out, handling messages, creating User/Room Variables and much more.

In addition to this API, a number of other specialized APIs provide the following features:

  • Game API: quick games, challenges, invitations, etc
  • Buyddy List API: managing buddy lists
  • MMO API: MMORoom creation, MMOItems, positioning, Area of Interest, etc
  • File API: access to files and directories

See also


new SFSApi()

Developers never istantiate the SFSApi class: this is done internally by the SmartFoxServer 2X API; get a reference to it using the Extension's getApi method.

Classes

HttpRequest
TaskScheduler

Members


<static> HttpMode

The HttpMode enum lists the POST and GET request modes.
See:
Properties:
Name Type Default Description
POST string post HTTP request mode is POST.
GET string get HTTP request mode is GET.

Methods


banUser(userToBan, modUser, banMessage, mode, delaySeconds)

Bans a user, preventing his reconnection for a configurable amount of time.

This operation allows to send a moderator message to the client, providing a number of seconds for reading it before the connection is closed.
The length of the banishment and the rules under which the ban can be removed are specified in the Zone configuration.

Parameters:
Name Type Description
userToBan SFSUser The SFSUser object representing the user to be banished.
modUser SFSUser The SFSUser object representing a moderator/administrator user executing the action; can be null to indicate the "Server" generically.
banMessage string A message from the moderator/administrator to be displayed to the user right before banishing him.
mode BanMode A ban mode among those provided by the BanMode enum.
delaySeconds number The delay in seconds before the disconnection is executed.

changeRoomCapacity(owner, targetRoom, maxUsers, maxSpectators)

Changes the capacity (maximum number of users/players and spectators) of the Room.

In case the Room size is shrunk, extra players or spectators will not be kicked out of the Room.

Parameters:
Name Type Description
owner SFSUser The SFSUser object representing the owner of the Room; if null, the authorization of the user to change the Room capacity is not checked.
targetRoom SFSRoom The SFSRoom object representing the Room to change the capacity to.
maxUsers number The new maximum number of users (aka players in Game Rooms).
maxSpectators number The new maximum number of spectators (for Game Rooms only).
Throws:
A SFSRoomException exception if the Room capacity couldn't be modified.

changeRoomName(owner, targetRoom, newName)

Renames a Room.
Parameters:
Name Type Description
owner SFSUser The SFSUser object representing the owner of the Room; if null, the authorization of the user to change the Room name is not checked.
targetRoom SFSRoom The SFSRoom object representing the Room to change the name to.
newName string The new Room name.
Throws:
A SFSRoomException exception if the new name is already assigned to another Room, its length is out of the range allowed by the Zone configuration or it contains bad words (if the Words Filter is active).

changeRoomPassword(owner, targetRoom, newPassword)

Changes the Room password and the Room password-protection state.

The password-protection state indicates if a Room is private and requires a password to access it. Passing a null or empty string makes the Room public. Passing a valid string as the password makes the Room private.

Parameters:
Name Type Description
owner SFSUser The SFSUser object representing the owner of the Room; if null, the authorization of the user to change the Room password-protection state is not checked.
targetRoom SFSRoom The SFSRoom object representing the Room to change the password-protection state to.
newPassword string The new password; null or empty string to remove the password protection.
Throws:
A SFSRoomException exception if the password-protection state couldn't be modified.

checkSecurePassword(session, originalPass, encryptedPass)

Checks the encrypted password sent by a user at login time against the one registered in the system (typically in the users database).
Parameters:
Name Type Description
session Session The client's Session object, usually provided by the SFSEventType.USER_LOGIN event.
originalPass string The original, un-encrypted password.
encryptedPass string The encrypted password sent by the client.
Returns:
true if the password is correct, false otherwise.
Type
boolean

createNPC(userName, zone, forceLogin)

Creates a connection-less Non-Player Character (NPC).

The server handles NPCs just like any other regular user, although there is no real, physical connection to the server (in other words no TCP connection is established).
NPCs can be recognized from the isNpc flag on the SFSUser object representing them, which is always set to true.

Notes:
  • NPCs must be created once the server engine is up and running. As the init method of the Extension runs before the engine is ready, you will need to wait for the SFSEventType.SERVER_READY event before being able to instantiate any NPC.
Parameters:
Name Type Description
userName string The name of the Non-Player Charachter.
zone SFSZone The SFSZone object representing the Zone the NPC should be created into.
forceLogin boolean If a user with the same name is already logged in the system and true is passed, that user will be disconnected before creating the NPC.
Throws:
A SFSLoginException exception if an error occurs during the NPC creation.
Returns:
The SFSUser object representing the NPC.
Type
SFSUser

createRoom(zone, settings [, owner] [, joinIt] [, roomToLeave] [, fireClientEvent] [, fireServerEvent])

Creates a new Room.

This method can create both regular Rooms and MMO Rooms, depending on the passed settings object.

See also:
Parameters:
Name Type Argument Default Description
zone SFSZone The SFSZone object representing the Zone the Room should be created into.
settings CreateRoomSettings | CreateMMORoomSettings The Room configuration object.
owner SFSUser <optional>
null The SFSUser object representing the owner of the Room; if null is passed, the "Server" will be the owner.
joinIt boolean <optional>
false If true, the Room will be joined by the owner right after the creation.
roomToLeave SFSRoom <optional>
null The SFSRoom object representing the Room to leave if the owner is supposed to join the new one; if null is passed, no previous Room will be left.
fireClientEvent boolean <optional>
false If true, a client-side ROOM_ADD event will be fired to notify the Room creation.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.ROOM_ADDED will be fired to notify the Room creation.
Throws:
A SFSCreateRoomException exception if an error occurs during the Room creation.
Returns:
The SFSRoom object representing the Room just created.
Type
SFSRoom
Examples

In this simple example we create an hidden, private chat Room.
In particular we also set a Room Variable and enable three specific events for the Room.

var crs = new CreateRoomSettings();
crs.setName("chat#371");
crs.setPassword("&12faGG");
crs.setGroupId("chats");
crs.setHidden(true);
crs.setMaxUsers(10);

// Set Room Variable
crs.setRoomVariables([new SFSRoomVariable("topic", "Board Games")]);

// Set Room permissions
crs.setRoomSettings(EnumSet.of(SFSRoomSettings.USER_ENTER_EVENT, SFSRoomSettings.USER_EXIT_EVENT, SFSRoomSettings.PUBLIC_MESSAGES));

// Create the Room
getApi().createRoom(getParentZone(), crs, null, false, null, true, true);

In this example we create an MMORoom for the SpaceWar game.
In particular we assign a Room Extension and configure the MMO-related features.

var crs = new CreateMMORoomSettings();
crs.setName("Sol");
crs.setMaxUsers(10000);
crs.setMaxSpectators(0);
crs.setGame(true);

// Set Room permissions
crs.setRoomSettings(EnumSet.of(SFSRoomSettings.USER_ENTER_EVENT, SFSRoomSettings.USER_EXIT_EVENT, SFSRoomSettings.USER_COUNT_CHANGE_EVENT, SFSRoomSettings.USER_VARIABLES_UPDATE_EVENT));

// Set the Extension attached to the Room
crs.setExtension(new CreateRoomSettings.RoomExtensionSettings("SpaceWar", "sfs2x.extensions.games.spacewar.SpaceWarRoomExtension"));

// Set MMORoom features
crs.setDefaultAOI(Vectors.newVec3D(900, 750));
crs.setUserMaxLimboSeconds(30);
crs.setProximityListUpdateMillis(20);
crs.setSendAOIEntryPoint(false);

// Create the Room
getApi().createRoom(getParentZone(), crs, null, false, null, true, true);

disconnectSession(session)

Removes a Session object, disconnecting the user associated with it (if one exists).
Parameters:
Name Type Description
session Session The client's Session object to be disconnected.

disconnectUser(user [, reason])

Disconnect a user from the server.
Parameters:
Name Type Argument Description
user SFSUser The SFSUser object representing the user to be disconnected.
reason ClientDisconnectionReason <optional>
One of the disconnection reasons provided in the ClientDisconnectionReason enum; the reason will be provided to the client in the client-side CONNECTION_LOST event.

findRooms(roomList, expression [, limit])

Find one or more Rooms in a list of Rooms matching the conditions set in a Match Expression.
Parameters:
Name Type Argument Default Description
roomList Array.<SFSRoom> An array of SFSRoom objects to search in.
expression MatchExpression The Match Expression setting the conditions to match.
limit number <optional>
10 When this limit is reached, the search is stopped; if set to 0, all matching Rooms are returned.
Returns:
A java.util.ArrayList Java collection containing the list of matching SFSRoom objects. This can be treated like native JavaScript array.
Type
ArrayList

findUsers(userList, expression [, limit])

Find one or more users in a list of users matching the conditions set in a Match Expression.
Parameters:
Name Type Argument Default Description
userList Array.<SFSUser> An array of SFSUser objects to search in.
expression MatchExpression The Match Expression setting the conditions to match.
limit number <optional>
10 When this limit is reached, the search is stopped; if set to 0, all matching users are returned.
Returns:
A java.util.ArrayList Java collection containing the list of matching SFSUser objects. This can be treated like native JavaScript array.
Type
ArrayList

getUserById(userId)

Retrieves a SFSUser object from its id property.
Parameters:
Name Type Description
userId number The id of the user to be retrieved.
Returns:
The SFSUser object representing the requested user.
Type
SFSUser

getUserByName(zone, name)

Retrieves a SFSUser object in a Zone from its name property.
Parameters:
Name Type Description
zone SFSZone The SFSZone object representing the Zone from which to retrieve the user.
name string The name of the user to be retrieved.
Returns:
The SFSUser object representing the requested user.
Type
SFSUser

getUserBySession(session)

Retrieves a SFSUser object from its client session.
Parameters:
Name Type Description
session Session The Session object of the user to be retrieved.
Returns:
The SFSUser object representing the requested user.
Type
SFSUser

getZoneByName(zoneName)

Returns a reference to the SFSZone object corresponding to the passed Zone name.
Parameters:
Name Type Description
zoneName string The name of the SFSZone object to be retrieved.
Returns:
A reference to a SFSZone class instance.
Type
SFSZone

joinRoom(user, roomToJoin [, password] [, asSpectator] [, roomToLeave] [, fireClientEvent] [, fireServerEvent])

Joins a user in a Room.
Parameters:
Name Type Argument Default Description
user SFSUser The SFSUser object representing the user to join in the Room.
roomToJoin SFSRoom The SFSRoom object representing the Room to make the user join.
password string <optional>
null The Room password, in case it is a private Room.
asSpectator boolean <optional>
false If true, the user will join the Room as a spectator.
roomToLeave SFSRoom <optional>
null The SFSRoom object representing the Room that the user must leave after joining the new one; if null is passed, no previous Room is left.
fireClientEvent boolean <optional>
false If true, the client-side ROOM_JOIN and USER_ENTER_ROOM events will be fired to notify the Room joining.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.USER_JOIN_ROOM will be fired to notify the Room joining.
Throws:
A SFSJoinRoomException exception if an error occurs during the Room joining process.
Example

In this example we retrieve a user by his name and join him in the "Lobby" Room available in the Extension's parent Zone.

// Get the target user and Room
var user = getApi().getUserbyName("bax");
var room = getParentZone().getRoomByName("Lobby");

// Make the user join the Room
getApi().joinRoom(user, room);

kickUser(userToKick, modUser, kickMessage, delaySeconds)

Kicks a user out of the server.

This operation allows to send a moderator message to the client, providing a number of seconds for reading it before the connection is closed.

Parameters:
Name Type Description
userToKick SFSUser The SFSUser object representing the user to be kicked out.
modUser SFSUser The SFSUser object representing a moderator/administrator user executing the action; can be null to indicate the "Server" generically.
kickMessage string A message from the moderator/administrator to be displayed to the user right before kicking him.
delaySeconds number The delay in seconds before the disconnection is executed.

leaveRoom(user, room [, fireClientEvent] [, fireServerEvent])

Makes a user leave a Room he joined previously.
Parameters:
Name Type Argument Default Description
user SFSUser The SFSUser object representing the user that should leave the Room.
room SFSRoom The SFSRoom object representing the Room that the user is going to leave.
fireClientEvent boolean <optional>
false If true, a client-side USER_EXIT_ROOM event will be fired to notify the action.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.USER_LEAVE_ROOM will be fired to notify the action.

logout(user)

Logs a user out of the current Zone.

This method can be useful to force a user leave the current Zone and join a new one.

Parameters:
Name Type Description
user SFSUser The SFSUser object representing the user to be logged out.

newHttpGetRequest(url, params, httpCallbackFn)

Creates and returns a new HttpRequest instance of type GET.

This is a factory method to create a SFSApi.HttpRequest instance.

See also:
Parameters:
Name Type Description
url string The address of the HTTP server to make the request to.
params object An object containing the parameters to send to the HTTP server.
httpCallbackFn httpCallbackFn The callback function that will process the response sent by the HTTP server.
Returns:
A new instance of the HttpRequest class.
Type
SFSApi.HttpRequest
Example

In this example we make an HTTP request to a dummy URL, passing an "id" parameter. We then process the response in the callback function.

function sendHttpRequest()
{
	var reqParams = { id: 25 };
	var httpReq = getApi().newHttpGetRequest('http://some.host.com/', reqParams, httpCallback);
	httpReq.execute();
}

function httpCallback(result)
{
	if (result.error)
		trace("HTTP request failed: " + result.error);
	else
	{
		trace("HTTP request successful: " + result.statusCode);
		trace(result.html);
	}
}

newHttpPostRequest(url, params, httpCallbackFn)

Creates and returns a new HttpRequest instance of type POST.

This is a factory method to create a SFSApi.HttpRequest instance.

See also:
Parameters:
Name Type Description
url string The address of the HTTP server to make the request to.
params object An object containing the parameters to send to the HTTP server.
httpCallbackFn httpCallbackFn The callback function that will process the response sent by the HTTP server.
Returns:
A new instance of the HttpRequest class.
Type
SFSApi.HttpRequest
Example

In this example we make an HTTP request to a dummy URL, passing an "id" parameter. We then process the response in the callback function.

function sendHttpRequest()
{
	var reqParams = { id: 25 };
	var httpReq = getApi().newHttpPostRequest('http://some.host.com/', reqParams, httpCallback);
	httpReq.execute();
}

function httpCallback(result)
{
	if (result.error)
		trace("HTTP request failed: " + result.error);
	else
	{
		trace("HTTP request successful: " + result.statusCode);
		trace(result.html);
	}
}

newScheduler( [threadPoolSize])

Creates and returns a new TaskScheduler instance.

This is a factory method to create a SFSApi.TaskScheduler instance.

See also:
Parameters:
Name Type Argument Default Description
threadPoolSize number <optional>
1 The number of threads backing the scheduler (recommended value between 1 and 4).
Returns:
A new instance of the TaskScheduler class.
Type
SFSApi.TaskScheduler
Example

In this example we create a dummy task in the Extension's init method; the task runs every 3 seconds and prints how many times it was executed. A try/catch block makes sure that the execution never stops, even if an error occurs in the task.

var stepCount = 0;
var scheduler;
var taskHandle;

// Initialize the Extension
function init()
{
	// Initialize the scheduler and schedule the task
	scheduler = getApi().newScheduler();
	taskHandle = scheduler.scheduleAtFixedRate(runner, 3000);
}

// Destroy the Extension
function destroy()
{
	if (taskHandle != null)
		taskHandle.cancel(true);
}

function runner()
{
	try
	{
		stepCount++;
		trace("I was called: ", stepCount, " times");
	}
	catch(err)
	{
		trace("An error occurred: ", err);
	}
}

playerToSpectator(user, targetRoom [, fireClientEvent] [, fireServerEvent])

Turns a player in a Game Room to spectator.
Parameters:
Name Type Argument Default Description
user SFSUser The SFSUser object representing the user to turn from player to spectator.
targetRoom SFSRoom The SFSRoom object representing the Room in which the player will be turned into a spectator.
fireClientEvent boolean <optional>
false If true, a client-side PLAYER_TO_SPECTATOR event will be fired to notify the change.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.PLAYER_TO_SPECTATOR will be fired to notify the change.
Throws:
A SFSRoomException exception if no spectator slot is available in the Game Room.

removeRoom(room [, fireClientEvent] [, fireServerEvent])

Removes a Room from its Zone.
Parameters:
Name Type Argument Default Description
room SFSRoom The SFSRoom object representing the Room that the user is going to leave.
fireClientEvent boolean <optional>
false If true, a client-side ROOM_REMOVE event will be fired to notify the Room removal.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.ROOM_REMOVED will be fired to notify the Room removal.

sendAdminMessage(sender, message, params, recipients)

Sends a message from an administrator to a list of clients.

The sender must be either an actual user with "Super User" privileges, or null. In this case the sender becomes the "Server" itself.

Parameters:
Name Type Description
sender SFSUser The SFSUser object representing the administrator sending the message; if null, the sender is the "server" itself.
message string The message to send.
params SFSObject A SFSObject containing custom parameters to be attached to the message.
recipients Array.<Session> An array of Session objects representing the clients to deliver the message to.

sendModeratorMessage(sender, message, params, recipients)

Sends a message from a moderator to a list of clients.

The sender must be either an actual user with "Super User" privileges, or null. In this case the sender becomes the "Server" itself.

Parameters:
Name Type Description
sender SFSUser The SFSUser object representing the moderator sending the message; if null, the sender is the "server" itself.
message string The message to send.
params SFSObject A SFSObject containing custom parameters to be attached to the message.
recipients Array.<Session> An array of Session objects representing the clients to deliver the message to.

sendObjectMessage(targetRoom, sender, message [, recipients])

Sends a data object from a user to a list of other users in a Room.

This method sends a custom SFSObject that can contain any data. Typically this is used to send game moves to players or other game/app related updates.
By default the message is sent to all users in the specified target Room, but a list of SFSUser object can be passed to specify which user in that Room should receive the message. The sender must be joined in the target Room too.

Parameters:
Name Type Argument Description
targetRoom SFSRoom The SFSRoom object representing the Room to send the data to.
sender SFSUser The SFSUser object representing the user sending the data to the target Room.
message SFSObject The data object to send.
recipients Array.<SFSUser> <optional>
An array of SFSUser objects representing the recipients to deliver the data to.

sendPrivateMessage(sender, recipient, message [, params])

Sends a private chat message from a user to another one.

The message is sent to both the sender and the recipient. The sender and recipient can be in any Room, or even not joined in any Room at all.

Parameters:
Name Type Argument Description
sender SFSUser The SFSUser object representing the user sending the message.
recipient SFSUser The SFSUser object representing the message recipient.
message string The chat message to send.
params SFSObject <optional>
A SFSObject containing custom parameters to be attached to the message (e.g. text color, font size, etc).

sendPublicMessage(targetRoom, sender, message [, params])

Sends a public chat message from a user.

The message is broadcast to all users in the target Room, including the sender himself.

Parameters:
Name Type Argument Description
targetRoom SFSRoom The SFSRoom object representing the Room to send the message to.
sender SFSUser The SFSUser object representing the user sending the message to the target Room.
message string The chat message to send.
params SFSObject <optional>
A SFSObject containing custom parameters to be attached to the message (e.g. text color, font size, etc).

setRoomVariables(user, targetRoom, variables [, fireClientEvent] [, fireServerEvent] [, overrideOwnership])

Sets the Room Variables for the passed Room.

Only new/updated variables are broadcast to the users in the target Room. A variable can also be deleted by setting it to null.

Parameters:
Name Type Argument Default Description
user SFSUser The SFSUser object representing the owner of the Room Variables; if null, the ownership is assigned to the "Server" itself.
targetRoom SFSRoom The SFSRoom object representing the Room in which to set the Room Variables.
variables Array.<SFSRoomVariable> An array of SFSRoomVariable objects to set.
fireClientEvent boolean <optional>
false If true, a client-side ROOM_VARIABLES_UPDATE event will be fired to notify the Room Variables creation/update.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.ROOM_VARIABLES_UPDATE will be fired to notify the Room Variables creation/update.
overrideOwnership boolean <optional>
false If true, the ownership of variables can be overridden.
Example

In this example we set a Room Variable for the "chat37" Room. The variable is set as "global", so its value is visible to users outside the Room too.

// Create Room Variable
var topicRoomVar = new SFSRoomVariable("topic", "Tabletop games", VariableType.STRING);
topicRoomVar.setGlobal(true);

// Get Room
var targetRoom = getParentZone().getRoomByName("chat37");

// Set Room Variable
getApi().setRoomVariables(null, targetRoom, [topicRoomVar], true);

setUserVariables(user, variables [, fireClientEvent] [, fireServerEvent])

Sets the User Variables for the passed user.

Only new/updated variables are broadcast to the users that can "see" the owner. A variable can also be deleted by setting it to null.

Parameters:
Name Type Argument Default Description
user SFSUser The SFSUser object representing the user for which the User Variables are set.
variables Array.<SFSUserVariable> An array of SFSUserVariable objects to set.
fireClientEvent boolean <optional>
false If true, a client-side USER_VARIABLES_UPDATE event will be fired to notify the User Variables creation/update.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.USER_VARIABLES_UPDATE will be fired to notify the User Variables creation/update.
Example

In this example we receive an Extension request which triggers the creation of a couple of User Variables for the requester.
Usually an Extension request is not necessary, because User Variables can be set by the client directly, but in this case we want to validate the "age" value sent by the client.

function init()
{
	// Register client request handlers
	addRequestHandler("setMyVars", onSetMyVarsRequest);
}

function onSetMyVarsRequest(inParams, sender)
{
	// Get parameters sent by the client
	var userNick = inParams.getUtfString("nick");
	var userAge = inParams.getInt("age");

	// Validate user age
	if (userAge >= 13)
	{
		// Create User Variables
		var userVar1 = new SFSUserVariable("nick", userNick, VariableType.STRING);
		var userVar2 = new SFSUserVariable("age", userAge, VariableType.INT);

		// Set User Variables
		getApi().setUserVariables(sender, [userVar1,userVar2], true);
	}
}

spectatorToPlayer(user, targetRoom [, fireClientEvent] [, fireServerEvent])

Turns a spectator in a Game Room to player.
Parameters:
Name Type Argument Default Description
user SFSUser The SFSUser object representing the user to turn from spectator to player.
targetRoom SFSRoom The SFSRoom object representing the Room in which the spectator will be turned into a player.
fireClientEvent boolean <optional>
false If true, a client-side SPECTATOR_TO_PLAYER event will be fired to notify the change.
fireServerEvent boolean <optional>
false If true, a server-side event of type SFSEventType.SPECTATOR_TO_PLAYER will be fired to notify the change.
Throws:
A SFSRoomException exception if no player slot is available in the Game Room.

subscribeRoomGroup(user, groupId)

Subscribes a user to a Room Group.

This action enables the user to receive events related to the Rooms belonging the passed Group.

Parameters:
Name Type Description
user SFSUser The SFSUser object representing the user to subscribe to a Room Group.
groupId string The name of the Group to subscribe.

unsubscribeRoomGroup(user, groupId)

Unsubscribes a user from a Room Group.

This action disables the user to receive events related to the Rooms belonging the passed Group.

Parameters:
Name Type Description
user SFSUser The SFSUser object representing the user to unsubscribe from a Room Group.
groupId string The name of the Group to unsubscribe.