SFS2X Docs / DevelopmentBasics / join-and-create-rooms
» Join and create Rooms
One of the fundamental building blocks in the SFS2X framework is the Room object. Rooms allow to arrange players so that they can "see" each other and interact together. A typical use of Rooms is to create different categories in a chatting application, different meeting locations in a virtual world or different places where to challenge other friends in all sort of games.
Rooms are created in two different ways.
- Statically: via the Zone Configurator module in the AdminTool. This is a useful way to create persistent Rooms in your Zone (e.g. a Lobby) that are initialized as soon as the SmartFoxServer instance is launched.
- Dynamically: rooms can be created and destroyed at runtime from either the client or the server. There is no difference between Rooms created from one or the other side, however on the server-side it is possible to fine tune certain aspects of Rooms that the client cannot access for security reasons.
For example, in our BasicExamples Zone (that we provide by default) there is one static Room called "The Lobby" which can be joined by any client after they have successfully logged in the Zone.
Joining a Room from the client API requires one line of code, in which a JoinRoomRequest is sent to the Server. The server will in turn respond with one of the following events:
- SFSEvent.ROOM_JOIN, if the operation was successful
- SFSEvent.ROOM_JOIN_ERROR, if an error occurred
As usual we will need to register the events in our main SmartFox class instance to be notified of the result of the join operation. This is the full code required to handle both cases (sfs is the SmartFox class instance).
... // Add room-related event listeners during the SmartFox instance setup sfs.AddEventListener(SFSEvent.ROOM_JOIN, OnRoomJoin); sfs.AddEventListener(SFSEvent.ROOM_JOIN_ERROR, OnRoomJoinError); ...
... // After the successful login, send the join Room request sfs.Send(new Sfs2X.Requests.JoinRoomRequest("The Lobby"));
private void OnRoomJoin(BaseEvent evt) { Room room = (Sfs2X.Entities.Room)evt.Params["room"]; Console.WriteLine("Room joined: " + room.name); } private void OnRoomJoinError(BaseEvent evt) { Console.WriteLine("Room join failed: " + (string)evt.Params["errorMessage"]); }
... // Add room-related event listeners during the SmartFox instance setup sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN, onRoomJoin, this); sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this); ...
... // After the successful login, send the join Room request sfs.send(new SFS2X.JoinRoomRequest("The Lobby"));
function onRoomJoin(evt) { console.log("Room joined: " + evt.room.name); } function onRoomJoinError(evt) { console.warn("Room join failed: " + evt.errorMessage); }
... // Add room-related event listeners during the SmartFox instance setup sfs.addEventListener(SFSEvent.ROOM_JOIN, onRoomJoin); sfs.addEventListener(SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError); ...
... // After the successful login, send the join Room request sfs.send(new JoinRoomRequest("The Lobby"));
private function onRoomJoin(evt:SFSEvent):void { trace("Room joined: " + evt.params.room.name); } private function onRoomJoinError(evt:SFSEvent):void { trace("Room join failed: " + evt.params.errorMessage); }
What could go wrong?
There are a number of possible things that could invalidate the attempt to join a Room.
- Room is full: each Room has a certain capacity. If the maximum number of users is reached no more clients will be able to join until a few slots are made available.
- Room doesn't exist: the Room id provided in the join request is not valid. No Room was found with that name or Room id (a unique Room number which can be used as an alternative to the name).
- Wrong password: Rooms can be made private via the use of a password. If you don't know this password or you have forgotten it, you won't be able to access the Room.
Joining one or more Rooms at the same time
In most cases the client will probably move from one Room to another leaving the previous Room after the new one is joined. This is the default mode in which SFS2X and its API operate by default.
There are situations, however, in which we need the client to remain joined in a Room (typically a Lobby) while entering another Room (maybe a game or chat Room). Let's examine the JoinRoomRequest constructor from the client API. The following arguments are available.
- id: the Room id can be either its name (string) or numeric id (int).
- password: (optional) a password if the Room is private.
- roomIdToLeave: (optional) indicates which Room should be left when the new one is joined with success. By default the last joined Room is used. However if the User is already joined in several other Rooms, here we can specify the Room that should be left. A value of -1 will indicate that no Room should be left.
- asSpectator: (optional) this option is available for game Rooms only and it allow the user to join as a "spectator" in the game (more on this later).
In order to keep track of the joined Rooms on the client-side, the API provide a couple of useful tools:
- the lastJoinedRoom property of the SmartFox class instance provides a reference to the last Room that has been joined; when this value is set to null, no Rooms have been joined yet;
- the joinedRooms property of the same class will provide a list of all Rooms that the client is currently joined in.
Finally the roomManager object in the SmartFox class allows to query the local Room List data.
Creating Rooms dynamically
Rooms can be created from code at any time (after the login) on both client and server-side. This is a quick example with the usual approach: add the listeners during the SmartFox class setup and send the appropriate request (CreateRoomRequest in this case).
... // Add room-related event listeners during the SmartFox instance setup sfs.AddEventListener(SFSEvent.ROOM_ADD, OnRoomCreate); sfs.AddEventListener(SFSEvent.ROOM_CREATION_ERROR, OnRoomCreateError); ...
// Set Room configuration RoomSettings settings = new RoomSettings("Piggy's Chat Room"); settings.MaxUsers = 40; settings.GroupId = "ChatGroup"; // Send the create Room request sfs.Send(new Sfs2X.Requests.CreateRoomRequest(settings));
private void OnRoomCreate(BaseEvent evt) { Room room = (Sfs2X.Entities.Room)evt.Params["room"]; Console.WriteLine("Room added: " + room.name); } private void OnRoomCreateError(BaseEvent evt) { Console.WriteLine("Room creation failed: " + (string)evt.Params["errorMessage"]); }
... // Add room-related event listeners during the SmartFox instance setup sfs.addEventListener(SFS2X.SFSEvent.ROOM_ADD, onRoomCreate, this); sfs.addEventListener(SFS2X.SFSEvent.ROOM_CREATION_ERROR, onRoomCreateError, this); ...
// Set Room configuration var settings = new SFS2X.RoomSettings("Piggy's Chat Room"); settings.maxUsers = 40; settings.groupId = "ChatGroup"; // Send the create Room request sfs.send(new SFS2X.CreateRoomRequest(settings));
function onRoomCreate(evt) { console.log("Room added: " + evt.room.name); } function onRoomCreateError(evt) { console.warn("Room creation failed: " + evt.errorMessage); }
... // Add room-related event listeners during the SmartFox instance setup sfs.addEventListener(SFSEvent.ROOM_ADD, onRoomCreate); sfs.addEventListener(SFSEvent.ROOM_CREATION_ERROR, onRoomCreateError); ...
// Set Room configuration var settings:RoomSettings = new RoomSettings("Piggy's Chat Room"); settings.maxUsers = 40; settings.groupId = "ChatGroup"; // Send the create Room request sfs.send(new CreateRoomRequest(settings));
private function onRoomCreate(evt:SFSEvent):void { trace("Room added: " + evt.params.room.name); } private function onRoomCreateError(evt:SFSEvent):void { trace("Room creation failed: " + evt.params.errorMessage); }
The RoomSetting class allows to specify a large number of parameters to fine tune all major and minor aspects of a Room. If the creation is successful the SFSEvent.ROOM_ADD event will be sent back to the client, otherwise an error message is notified in the SFSEvent.ROOM_CREATION_ERROR event. There could be several reasons why the Room cannot be created.
- Lack of User Permission: depending on your configuration of the Privilege Manager a User with a certain permission profile might not be allowed to create new Rooms in the system.
- Duplicate Room name: two Rooms can't have the same name in the same Zone. The check is applied in case-sensitive mode.
- Bad words in Room name: if a Word Filter is configured in the Zone and applied to Room names (see Zone Configurator in the AdminTool) the creation could be refused because swear words are detected in the Room name.
- Maximum number of user-created Rooms is reached: for security reasons the Zone is configured with a configurable maximum number of Rooms that can be created at once by each user. If a client has already created three Rooms (which are all active) and the limit is set to three, a new attempt to create a Room will fail until one of the previous Rooms is removed.
- Maximum number of Rooms in the Zone is reached: a Zone can be configured with a maximum number of Rooms. When this value is reached, no more Rooms can be created until some of the old Rooms are removed.
You can learn all the details about the RoomSettings parameters in the API documentation (both client and server).
Basic Room concepts
In the SFS2X framework Rooms are a quite sophisticated tool that can be configured in every minor detail. This article is not intended to analyze all these aspects. If you want to learn all the details we suggest to consult this guide to Room architecture.
In this section we are going to mention two different types of Rooms: game Rooms and non-games Rooms (or "regular" Rooms). A third type also exists (MMO Rooms), but we will skip them for now.
- Regular Rooms: by default a new Room is created with the isGame flag set to false. You can use these Rooms for all purposes such as the creation of a Lobby, chat Rooms, conference Rooms, etc.
- Game Rooms: when the isGame flag is set to true the Room offers a couple of extra functionalities that are essential for most games.
- Automatic assignment of player IDs: each user is automatically assigned a unique player id value from 1 to N, providing the developer a simple way to recognize each player. Player IDs are managed and assigned by the server transparently.
- Support for non-player users (spectators): the Room can be created with a certain number of player slots and spectator slots (e.g. 2 players, and 8 spectators). This will enable other users to join the Room as non-players and watch the game. If one or more players leave the game the developer could allow spectators to join the game (see the SpectatorToPlayerRequest and PlayerToSpectatorRequest requests).
When creating a game Room always remember to set the isGame flag and configure the maximum number of players and spectators allowed in that Room.
Advanced Game Rooms and the Game API
The SFS2X platform provides a set of client and server APIs specifically designed for game creation and management, including public and private games, game invitations, User and Room matching and lots more.
The SFSGame class, which is found both on the client and server side of the API, extends the Room object providing dozens of new functionalities that enable developers to create advanced player matching, challenges and game invitations in a snap.
We highly recommend to take a look at the Game API article for more information.