new SFSApi()
Classes
Members
-
<static> HttpMode
-
The HttpMode enum lists the POST and GET request modes.
See:
- SFSApi.HttpRequest class
Properties:
Name Type Default Description POSTstring post HTTP request mode is POST. GETstring 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 userToBanSFSUser The
SFSUser object representing the user to be banished.modUserSFSUser The
SFSUser object representing a moderator/administrator user executing the action; can be nullto indicate the "Server" generically.banMessagestring A message from the moderator/administrator to be displayed to the user right before banishing him. modeBanMode A ban mode among those provided by the BanMode enum. delaySecondsnumber 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 ownerSFSUser The
SFSUser object representing the owner of the Room; if null, the authorization of the user to change the Room capacity is not checked.targetRoomSFSRoom The
SFSRoom object representing the Room to change the capacity to.maxUsersnumber The new maximum number of users (aka players in Game Rooms). maxSpectatorsnumber 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 ownerSFSUser The
SFSUser object representing the owner of the Room; if null, the authorization of the user to change the Room name is not checked.targetRoomSFSRoom The
SFSRoom object representing the Room to change the name to.newNamestring 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
nullor empty string makes the Room public. Passing a valid string as the password makes the Room private.Parameters:
Name Type Description ownerSFSUser 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.targetRoomSFSRoom The
SFSRoom object representing the Room to change the password-protection state to.newPasswordstring The new password; nullor 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 sessionSession The client's
Session object, usually provided by the
SFSEventType.USER_LOGIN event.originalPassstring The original, un-encrypted password. encryptedPassstring The encrypted password sent by the client. Returns:
trueif the password is correct,falseotherwise.- 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 totrue.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 userNamestring The name of the Non-Player Charachter. zoneSFSZone The
SFSZone object representing the Zone the NPC should be created into.forceLoginboolean If a user with the same name is already logged in the system and trueis 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
- 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
-
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:
- CreateRoomSettings class
- CreateMMORoomSettings class
- GameApi#createGame method
Parameters:
Name Type Argument Default Description zoneSFSZone The
SFSZone object representing the Zone the Room should be created into.settingsCreateRoomSettings | CreateMMORoomSettings The Room configuration object. ownerSFSUser <optional>
null The
SFSUser object representing the owner of the Room; if nullis passed, the "Server" will be the owner.joinItboolean <optional>
false If true, the Room will be joined by the owner right after the creation.roomToLeaveSFSRoom <optional>
null The
SFSRoom object representing the Room to leave if the owner is supposed to join the new one; if nullis passed, no previous Room will be left.fireClientEventboolean <optional>
false If true, a client-side ROOM_ADD event will be fired to notify the Room creation.fireServerEventboolean <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 sessionSession The client's
Session object to be disconnected. -
disconnectUser(user [, reason])
-
Disconnect a user from the server.
Parameters:
Name Type Argument Description userSFSUser The
SFSUser object representing the user to be disconnected.reasonClientDisconnectionReason <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 roomListArray.<SFSRoom> An array of
SFSRoom objects to search in.expressionMatchExpression The Match Expression setting the conditions to match. limitnumber <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 userListArray.<SFSUser> An array of
SFSUser objects to search in.expressionMatchExpression The Match Expression setting the conditions to match. limitnumber <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 userIdnumber 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 zoneSFSZone The
SFSZone object representing the Zone from which to retrieve the user.namestring 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 sessionSession 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 zoneNamestring 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 userSFSUser The
SFSUser object representing the user to join in the Room.roomToJoinSFSRoom The
SFSRoom object representing the Room to make the user join.passwordstring <optional>
null The Room password, in case it is a private Room. asSpectatorboolean <optional>
false If true, the user will join the Room as a spectator.roomToLeaveSFSRoom <optional>
null The
SFSRoom object representing the Room that the user must leave after joining the new one; if nullis passed, no previous Room is left.fireClientEventboolean <optional>
false If true, the client-side ROOM_JOIN and USER_ENTER_ROOM events will be fired to notify the Room joining.fireServerEventboolean <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 userToKickSFSUser The
SFSUser object representing the user to be kicked out.modUserSFSUser The
SFSUser object representing a moderator/administrator user executing the action; can be nullto indicate the "Server" generically.kickMessagestring A message from the moderator/administrator to be displayed to the user right before kicking him. delaySecondsnumber 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 userSFSUser The
SFSUser object representing the user that should leave the Room.roomSFSRoom The
SFSRoom object representing the Room that the user is going to leave.fireClientEventboolean <optional>
false If true, a client-side USER_EXIT_ROOM event will be fired to notify the action.fireServerEventboolean <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 userSFSUser 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:
- SFSApi.HttpRequest class
Parameters:
Name Type Description urlstring The address of the HTTP server to make the request to. paramsobject An object containing the parameters to send to the HTTP server. httpCallbackFnhttpCallbackFn 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:
- SFSApi.HttpRequest class
Parameters:
Name Type Description urlstring The address of the HTTP server to make the request to. paramsobject An object containing the parameters to send to the HTTP server. httpCallbackFnhttpCallbackFn 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:
- SFSApi.TaskScheduler class
Parameters:
Name Type Argument Default Description threadPoolSizenumber <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 userSFSUser The
SFSUser object representing the user to turn from player to spectator.targetRoomSFSRoom The
SFSRoom object representing the Room in which the player will be turned into a spectator.fireClientEventboolean <optional>
false If true, a client-side PLAYER_TO_SPECTATOR event will be fired to notify the change.fireServerEventboolean <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 roomSFSRoom The
SFSRoom object representing the Room that the user is going to leave.fireClientEventboolean <optional>
false If true, a client-side ROOM_REMOVE event will be fired to notify the Room removal.fireServerEventboolean <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 senderSFSUser The
SFSUser object representing the administrator sending the message; if null, the sender is the "server" itself.messagestring The message to send. paramsSFSObject A SFSObject containing custom parameters to be attached to the message. recipientsArray.<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 senderSFSUser The
SFSUser object representing the moderator sending the message; if null, the sender is the "server" itself.messagestring The message to send. paramsSFSObject A SFSObject containing custom parameters to be attached to the message. recipientsArray.<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 targetRoomSFSRoom The
SFSRoom object representing the Room to send the data to.senderSFSUser The
SFSUser object representing the user sending the data to the target Room.messageSFSObject The data object to send. recipientsArray.<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 senderSFSUser The
SFSUser object representing the user sending the message.recipientSFSUser The
SFSUser object representing the message recipient.messagestring The chat message to send. paramsSFSObject <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 targetRoomSFSRoom The
SFSRoom object representing the Room to send the message to.senderSFSUser The
SFSUser object representing the user sending the message to the target Room.messagestring The chat message to send. paramsSFSObject <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 userSFSUser The
SFSUser object representing the owner of the Room Variables; if null, the ownership is assigned to the "Server" itself.targetRoomSFSRoom The
SFSRoom object representing the Room in which to set the Room Variables.variablesArray.<SFSRoomVariable> An array of SFSRoomVariable objects to set. fireClientEventboolean <optional>
false If true, a client-side ROOM_VARIABLES_UPDATE event will be fired to notify the Room Variables creation/update.fireServerEventboolean <optional>
false If true, a server-side event of type
SFSEventType.ROOM_VARIABLES_UPDATE will be fired to notify the Room Variables creation/update.overrideOwnershipboolean <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 userSFSUser The
SFSUser object representing the user for which the User Variables are set.variablesArray.<SFSUserVariable> An array of SFSUserVariable objects to set. fireClientEventboolean <optional>
false If true, a client-side USER_VARIABLES_UPDATE event will be fired to notify the User Variables creation/update.fireServerEventboolean <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 userSFSUser The
SFSUser object representing the user to turn from spectator to player.targetRoomSFSRoom The
SFSRoom object representing the Room in which the spectator will be turned into a player.fireClientEventboolean <optional>
false If true, a client-side SPECTATOR_TO_PLAYER event will be fired to notify the change.fireServerEventboolean <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 userSFSUser The
SFSUser object representing the user to subscribe to a Room Group.groupIdstring 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 userSFSUser The
SFSUser object representing the user to unsubscribe from a Room Group.groupIdstring The name of the Group to unsubscribe.