### Android Connector Example Setup Source: https://docs2x.smartfoxserver.com/ExamplesAndroid/android-connector This example is provided as an Android Studio project. Open the project directly in Android Studio to run it on an Android device. No specific setup beyond having Android Studio installed is required. -------------------------------- ### Install and run SmartFoxServer 2X on Unix Source: https://docs2x.smartfoxserver.com/GettingStarted/install-unix Commands to navigate to the installation directory, extract the archive, and start the server script. ```bash $ cd /home/fozzie $ tar xf SFS2X_unix_2_12_0.tar.gz $ cd SmartFoxServer_2X/SFS2X/ $ ./sfs2x.sh ``` -------------------------------- ### Start SmartFoxServer 2X Service Source: https://docs2x.smartfoxserver.com/GettingStarted/install-linux Navigate to the installation directory and use the sfs2x-service script to start the server. ```bash $ cd /home/fozzie/SmartFoxServer_2X/SFS2X/ $ ./sfs2x-service start ``` -------------------------------- ### Generic Event Listener Setup Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/SFSEvent.html This example demonstrates the general approach to listening for events in SmartFoxServer 2X. It shows how to initialize the client, add an event listener, and connect to the server. Ensure the server is running at the specified address. ```javascript var sfs = null; function init() { // Create SmartFox client instance sfs = new SFS2X.SmartFox(); // Add event listener for connection sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this); // Connect to the server sfs.connect("127.0.0.1", 8080); } // Handle connection event function onConnection(evtParams) { if (evtParams.success) console.log("Connected to SmartFoxServer 2X!"); else console.log("Connection failed. Is the server running at all?"); } ``` -------------------------------- ### Basic Server Connection Example (Unity C#) Source: https://docs2x.smartfoxserver.com/ExamplesUnity/introduction Illustrates the fundamental process of establishing a connection to the SmartFoxServer 2X. This example may include optional protocol encryption. ```csharp using UnityEngine; using Sfs2X.Core; using Sfs2X.Requests; public class ConnectionExample : MonoBehaviour { void Start () { // Get the SmartFox instance SmartFox sfs = new SmartFox(true); // Add event listeners sfs.AddEventListener(SFSEvent.CONNECTION_SUCCESS, OnConnectionSuccess); sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost); sfs.AddEventListener(SFSEvent.LOGIN, OnLogin); // Connect to the server sfs.Connect("127.0.0.1", 9933); } void OnConnectionSuccess(BaseEvent evt) { Debug.Log("Connection successful!"); // Login to the server sfs.Send(new LoginRequest("MyUsername", "", "MyZone")); } void OnConnectionLost(BaseEvent evt) { Debug.Log("Connection lost."); } void OnLogin(BaseEvent evt) { Debug.Log("Logged in successfully!"); } } ``` -------------------------------- ### Login Request Example Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/SmartFox.html This example demonstrates how to send a login request to the SmartFoxServer. ```APIDOC ## Login Request ### Description Sends a login request to the SmartFoxServer. ### Method `sfs.send()` ### Endpoint N/A (Client-side method) ### Parameters #### Request Body - **request** (LoginRequest) - Required - A `LoginRequest` object containing username, password, zone, and potentially a spectator mode flag. ### Request Example ```javascript sfs.send(new SFS2X.LoginRequest("KermitTheFrog", "kermitPwd", null, "TheMuppetZone")); ``` ### Response N/A (Response is handled by server callbacks) ``` -------------------------------- ### Join Room Request Example Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/SmartFox.html This example shows how to send a request to join a specific room in SmartFoxServer. ```APIDOC ## Join Room Request ### Description Sends a request to join a specified room. ### Method `sfs.send()` ### Endpoint N/A (Client-side method) ### Parameters #### Request Body - **request** (JoinRoomRequest) - Required - A `JoinRoomRequest` object specifying the room name. ### Request Example ```javascript sfs.send(new SFS2X.JoinRoomRequest("Lobby")); ``` ### Response N/A (Response is handled by server callbacks) ``` -------------------------------- ### Start Game Logic Source: https://docs2x.smartfoxserver.com/ExamplesGodot/tic-tac-toe Initializes the game state and notifies all users in the room that the game has started. ```Java public void startGame(){ if (gameStarted) throw new IllegalStateException("Game is already started"); // Reset state gameStarted = true; gameBoard.reset(); // No turn assigned? let's start with player 1 if (whoseTurn == null) whoseTurn = getParentRoom().getUserByPlayerId(1); // Send START event to clients with: // - the active player // - the total wins of player 1 and 2 ISFSObject outParams = new SFSObject(); outParams.putInt("t", whoseTurn.getPlayerId()); outParams.putInt("p1w", wins[1]); outParams.putInt("p2w", wins[2]); send("start", outParams, getParentRoom().getUserList());} ``` -------------------------------- ### MMOItem Example Usage Source: https://docs2x.smartfoxserver.com/api-docs/javadoc/server/com/smartfoxserver/v2/mmo/MMOItem.html An example demonstrating how to create and position an MMOItem within an MMORoom using the SmartFoxServer API. ```APIDOC ## MMOItem Example ### Description This example shows how to prepare variables for an MMOItem, create the item, and then set its position in an MMORoom using the `SFSMMOApi`. ### Code Example ```java // Prepare the variables List vars = new LinkedList(); vars.add(new MMOItemVariable("type", "1")); // identifies the type of bonus based on our game rules vars.add(new MMOitemVariable("val", 100)); // the value of the bonus // Create the item MMOItem bonus = new MMOItem(vars); // Access the MMO API ISFSMMOApi mmoApi = SmartfoxServer.getInstance().getAPIManager().getMMOApi; // Set the Item in the room at specific coordinates mmoApi.setMMOItemPosition(bonus, new Vec3D(10, 20, 5), theMMORoom); ``` ### Notes - The `theMMORoom` object is assumed to be an existing `MMORoom` instance. - After placement, a `PROXIMITY_LIST_UPDATE` will be sent to users within range of the item. ``` -------------------------------- ### Start SmartFoxServer 2X Service Source: https://docs2x.smartfoxserver.com/GettingStarted/install-macosx Use this command to start the SmartFoxServer 2X service from the terminal. Ensure you are in the SFS2X directory. ```bash ./sfs2x-service start ``` -------------------------------- ### Start HttpServer Method Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/04392ae2-02ed-cbd7-1989-ff26b90f220d.htm Initializes the server to listen for incoming requests. Throws an InvalidOperationException if the server fails to start or lacks a required certificate for secure connections. ```C# public void Start() ``` -------------------------------- ### Change Room Capacity Example Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/5c5da138-5dfe-fb1f-eaeb-a38243bee4c2.htm Example demonstrating how to send a capacity change request and handle the resulting success or error events. ```C# void SomeMethod() { sfs.AddEventListener(SFSEvent.ROOM_CAPACITY_CHANGE, OnRoomCapacityChange); sfs.AddEventListener(SFSEvent.ROOM_CAPACITY_CHANGE_ERROR, OnRoomCapacityChangeError); Room theRoom = sfs.GetRoomByName("Gonzo's Room"); // Resize the Room so that it allows a maximum of 100 users and zero spectators sfs.Send( new ChangeRoomCapacityRequest(theRoom, 100, 0) ); } void OnRoomCapacityChange(BaseEvent evt) { Room room = (Room)evt.Params["room"]; Console.WriteLine("The capacity of Room " + room.Name + " was changed successfully"); // .Net / Unity System.Diagnostics.Debug.WriteLine("The capacity of Room " + room.Name + " was changed successfully"); // UWP } void OnRoomCapacityChangeError(BaseEvent evt) { Console.WriteLine("Room capacity change failed: " + (string)evt.Params["errorMessage"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("Room capacity change failed: " + (string)evt.Params["errorMessage"]); // UWP } ``` -------------------------------- ### Godot Project Setup for Lobby Basics Source: https://docs2x.smartfoxserver.com/ExamplesGodot/lobby-basics Instructions for setting up the Godot project for the Lobby Basics tutorial. Ensure the SmartFoxServer 2X client API DLLs are in the project's root folder. ```text 1. unzip the examples package; 2. launch Godot, click on the _Import_ button and navigate to the _SFS_LobbyBasics_GD4_ folder; 3. click the **Build button** in the top right corner of the Godot editor before running the example. ``` -------------------------------- ### Create a New Game with SFSGameSettings Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/475b54d7-0e20-b1af-a5ab-35554b27a5b9.htm Example demonstrating how to configure game settings and send a CreateSFSGameRequest, along with handling room creation events. ```C# void SomeMethod() { sfs.AddEventListener(SFSEvent.ROOM_ADD, OnRoomCreated); sfs.AddEventListener(SFSEvent.ROOM_CREATION_ERROR, OnRoomError); // Prepare the settings for a public game SFSGameSettings settings = new SFSGameSettings("DartsGame"); settings.MaxUsers = 2; settings.MaxSpectators = 8; settings.IsPublic = true; settings.MinPlayersToStartGame = 2; settings.NotifyGameStarted = true; // Set the matching expression to filter users joining the Room settings.PlayerMatchExpression = new MatchExpression("bestScore", NumberMatch.GREATER_THAN, 100); // Set a Room Variable containing the description of the game List roomVars = new List(); roomVars.Add(new SFSRoomVariable("desc", "Darts game, public, bestScore > 100")); settings.variables = roomVars; // Create the game smartFox.Send( new CreateSFSGameRequest(settings) ); } void OnRoomCreated(BaseEvent evt) { Console.WriteLine("Room created: " + (Room)evt.Params["room"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("Room created: " + (Room)evt.Params["room"]); // UWP } void OnRoomError(BaseEvent evt) { Console.WriteLine("Room creation failed: " + (string)evt.Params["errorMessage"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("Room creation failed: " + (string)evt.Params["errorMessage"]); // UWP } ``` -------------------------------- ### Get WebSocketBehavior Session ID Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/24176dcc-1339-0897-d05e-ca41825103ae.htm Use this property to get the unique identifier for a WebSocket session. Returns null if the session has not yet started. ```csharp public string ID { get; } ``` -------------------------------- ### Install SFS2X as Daemon (SystemV init) Source: https://docs2x.smartfoxserver.com/GettingStarted/install-linux Create a symbolic link in the appropriate /etc/rcX.d folder to launch SFS2X as a daemon on startup. Requires root privileges. ```bash $ cd /etc/rc5.d $ ln -s /home/fozzie/SmartFoxServer_2X/SFS2X/SFS2X/sfs2x-service S99sfs2X ``` -------------------------------- ### Get Minimum Players to Start Game Source: https://docs2x.smartfoxserver.com/api-docs/javadoc/server/com/smartfoxserver/v2/game/SFSGame.html Retrieves the minimum number of players required for the game to start. This value is typically set during game creation. ```java public int getMinPlayersToStartGame() ``` -------------------------------- ### GET HttpListener.IsListening Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/20141f5f-30a2-9278-c26f-9dbbb3cb288f.htm Retrieves the current status of the HttpListener to determine if it has been started. ```APIDOC ## GET HttpListener.IsListening ### Description Gets a value indicating whether the listener has been started. ### Property Value - **IsListening** (Boolean) - true if the listener has been started; otherwise, false. ### Reference - **Namespace**: Sfs2X.WebSocketSharp.Net - **Assembly**: SmartFox2X (in SmartFox2X.dll) Version: 1.8.0.0 (1.8.0) ``` -------------------------------- ### Quickly Join or Create a Room Example Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/6647f7b7-9233-6491-0262-4dada143ac4d.htm This example demonstrates how to use QuickJoinOrCreateRoomRequest to find and join a public room based on a MatchExpression, or create a new one if none exists. It includes event listeners for room addition and joining, and sets up RoomSettings for potential new room creation. ```csharp void SomeMethod() { sfs.AddEventListener(SFSEvent.ROOM_ADD, OnRoomAdd); sfs.AddEventListener(SFSEvent.ROOM_JOIN, OnRoomJoin); // Create a matching expression to find a Darts game with a "maxBet" variable less than 100 MatchExpression exp = new MatchExpression("type", StringMatch.EQUALS, "Darts").And("maxBet", NumberMatch.LESS_THAN, 100); // Set the Room settings to create a new Room if a matching one is not found RoomSettings settings = new RoomSettings("NewRoom__" + new System.Random().Next()); settings.GroupId = "games"; settings.IsPublic = true; settings.IsGame = true; settings.MaxUsers = 10; settings.MinPlayersToStartGame = 2; // Set requirements to allow users find the Room (see match expression above) in Room Variables List roomVars = new List(); roomVars.Add(new SFSRoomVariable("type", "Darts")); roomVars.Add(new SFSRoomVariable("maxBet", 50)); settings.Variables = roomVars; // Search (or create) and join a public Room within the "games" Group sfs.Send(new QuickJoinOrCreateRoomRequest(exp, new List(){"games"}, settings)); } void OnRoomAdd(BaseEvent evt) { Console.WriteLine("Room created: " + (Room)evt.Params["room"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("Room created: " + (Room)evt.Params["room"]); // UWP } void OnRoomJoin(BaseEvent evt) { Console.WriteLine("Successfully joined Room: " + (Room)evt.Params["room"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("Successfully joined Room: " + (Room)evt.Params["room"]); // UWP } ``` -------------------------------- ### Get SFS2X Client and Add Listeners in Start Source: https://docs2x.smartfoxserver.com/ExamplesUnity/lobby-basics Called when the scene starts. Retrieves the SmartFox instance from the GameManager singleton and adds necessary event listeners. ```csharp private void Start(){ // Set a reference to the SmartFox client instance sfs = gm.GetSfsClient(); ... // Add event listeners AddSmartFoxListeners(); ... } ``` -------------------------------- ### Start SmartFoxServer 2X Service with Sudo Source: https://docs2x.smartfoxserver.com/GettingStarted/install-macosx If running the server as a service or daemon, you may need to use the 'sudo' command to start the SmartFoxServer 2X service. This is common in Unix-like environments. ```bash sudo ./sfs2x-service start ``` -------------------------------- ### Room Management Example (Unity C#) Source: https://docs2x.smartfoxserver.com/ExamplesUnity/introduction Demonstrates how to manage rooms within SmartFoxServer 2X, including joining and creating rooms. This is essential for multiplayer game structure. ```csharp using UnityEngine; using Sfs2X.Core; using Sfs2X.Requests; using Sfs2X.Entities.Rooms; public class RoomManagementExample : MonoBehaviour { private SmartFox sfs; void Start() { sfs = new SmartFox(true); sfs.AddEventListener(SFSEvent.CONNECTION_SUCCESS, OnConnectionSuccess); sfs.AddEventListener(SFSEvent.LOGIN, OnLogin); sfs.AddEventListener(SFSEvent.ROOM_JOIN, OnRoomJoin); sfs.Connect("127.0.0.1", 9933); } void OnConnectionSuccess(BaseEvent evt) { sfs.Send(new LoginRequest("User", "", "MyZone")); } void OnLogin(BaseEvent evt) { // Join a specific room sfs.Send(new JoinRoomRequest("MyGameRoom")); } void OnRoomJoin(BaseEvent evt) { Room joinedRoom = (Room)evt.Params["room"]; Debug.Log("Joined room: " + joinedRoom.Name); // You can now interact within the room } } ``` -------------------------------- ### WebSocketServer.IsListening Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/f050b3eb-5c35-f33f-575a-70ba03ddf99a.htm Gets a value indicating whether the WebSocket server has started listening for incoming connections. ```APIDOC ## WebSocketServer.IsListening Property ### Description Gets a value indicating whether the server has started. ### Method GET ### Endpoint N/A (This is a property, not an endpoint) ### Parameters None ### Request Body None ### Response #### Success Response (200) - **IsListening** (Boolean) - true if the server has started; otherwise, false. #### Response Example ```json { "IsListening": true } ``` ### Reference - WebSocketServer Class - Sfs2X.WebSocketSharp.Server Namespace ``` -------------------------------- ### Get Session Start Time - C# Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/132839b7-4aff-a47c-8bc9-e0f37999875e.htm Retrieves the time when the WebSocket session was established. This property is read-only. ```csharp DateTime StartTime { get; } ``` -------------------------------- ### Buddy Messenger Connector (JavaScript) Source: https://docs2x.smartfoxserver.com/ExamplesJS/buddy-messenger Establishes a connection to the SmartFoxServer. This is a common starting point for client-side examples. ```javascript import { SmartFox } from "./smartfox/SmartFox"; const sfs = new SmartFox(); sfs.addEventListener(SmartFox.Events.CONNECTION_SUCCESS, onConnection); sfs.addEventListener(SmartFox.Events.CONNECTION_LOST, onConnectionLost); sfs.addEventListener(SmartFox.Events.LOGIN, onLogin); sfs.connect("127.0.0.1", 9933); function onConnection(evt) { console.log("Connection successful!"); sfs.login("ExampleUser", "", "BasicExamples"); } function onConnectionLost(evt) { console.log("Connection lost."); } function onLogin(evt) { console.log("Logged in as: " + evt.data.username); } ``` -------------------------------- ### Initiate Server Connection Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/SFSEvent.html This example demonstrates how to initiate a connection to a SmartFoxServer 2X instance. It involves creating a SmartFox client instance, adding a listener for the CONNECTION event, and calling the connect method with the server's IP address and port. The onConnection function handles the success or failure of the connection attempt. ```javascript function someMethod() { sfs = new SFS2X.SmartFox(); sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this); sfs.connect(127.0.0.1, 8080); } function onConnection(evtParams) { if (evtParams.success) console.log("Connection established"); else console.log("Connection failed"); } ``` -------------------------------- ### Connect to SFS2X in Unity Source: https://docs2x.smartfoxserver.com/DevelopmentBasics/connection-phase This example demonstrates how to initialize the SmartFox client, set connection parameters, and handle connection events within a Unity MonoBehaviour. It includes essential lifecycle management such as processing events in Update and cleaning up on application quit. ```csharp public class Connector : MonoBehaviour{ public Button button; private SmartFox sfs; //---------------------------------------------------------- // Unity callback methods //---------------------------------------------------------- void Start() { // Add click listener to UI button button.onClick.AddListener(OnButtonClick); } void Update() { // As Unity is not thread safe, we process the queued up callbacks on every frame if (sfs != null) sfs.ProcessEvents(); } void OnApplicationQuit() { // Always disconnect before quitting if (sfs != null && sfs.IsConnected) sfs.Disconnect (); } //---------------------------------------------------------- // Public methods for UI //---------------------------------------------------------- public void OnButtonClick() { // Disable button button.interactable = false; Debug.Log("Now connecting..."); // Initialize SFS2X client sfs = new SmartFox(); // Add event listeners sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection); sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost); // Set connection parameters ConfigData cfg = new ConfigData(); cfg.Host = "127.0.0.1"; cfg.Port = 9933; // Connect to SFS2X sfs.Connect(cfg); } //---------------------------------------------------------- // SmartFoxServer event listeners //---------------------------------------------------------- private void OnConnection(BaseEvent evt) { if ((bool)evt.Params["success"]) { Debug.Log("Connection established successfully"); Debug.Log("SFS2X API version: " + sfs.Version); } else { Debug.LogError("Connection failed; is the server running at all?"); // Remove SFS2X listeners and re-enable button reset(); } } private void OnConnectionLost(BaseEvent evt) { Debug.LogWarning("Connection was lost; reason is: " + (string)evt.Params["reason"]); // Remove SFS2X listeners and re-enable button reset(); } //---------------------------------------------------------- // Private helper methods //---------------------------------------------------------- private void reset() { // Remove SFS2X listeners sfs.RemoveEventListener(SFSEvent.CONNECTION, OnConnection); sfs.RemoveEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost); sfs = null; // Enable button button.interactable = true; }} ``` -------------------------------- ### WebSocketServer.SslConfiguration Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/f5eda671-57e5-dcdd-f433-3dd25dae42b2.htm Gets the configuration for secure connection. This configuration must be set before starting the server if secure connections are to be used. ```APIDOC ## WebSocketServer.SslConfiguration Property ### Description Gets the configuration for secure connection. ### Method GET ### Endpoint N/A (Property Access) ### Parameters N/A ### Request Body N/A ### Response #### Success Response (200) - **SslConfiguration** (ServerSslConfiguration) - A ServerSslConfiguration that represents the configuration used to provide secure connections. #### Response Example ```json { "SslConfiguration": { "//": "Example ServerSslConfiguration object" } } ``` ### Exceptions - **InvalidOperationException**: This instance does not provide secure connections. ``` -------------------------------- ### WebSocketServer.AuthenticationSchemes Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/d72cceb6-119b-265c-2f4a-0afdddde89d4.htm Gets or sets the scheme used to authenticate the clients. This property can be set before the server starts listening. The default value is Anonymous. ```APIDOC ## WebSocketServer.AuthenticationSchemes Property ### Description Gets or sets the scheme used to authenticate the clients. ### Method GET, SET ### Endpoint N/A (Class Property) ### Parameters #### Property Value - **AuthenticationSchemes** (AuthenticationSchemes) - Required - One of the AuthenticationSchemes enum values. It represents the scheme used to authenticate the clients. The default value is Anonymous. The set operation does nothing if the server has already started or it is shutting down. ### Request Example ```csharp // Setting authentication scheme webSocketServer.AuthenticationSchemes = AuthenticationSchemes.Basic; // Getting authentication scheme AuthenticationSchemes currentScheme = webSocketServer.AuthenticationSchemes; ``` ### Response #### Success Response (Property Value) - **AuthenticationSchemes** (AuthenticationSchemes) - The current authentication scheme. #### Response Example ```json { "AuthenticationSchemes": "Basic" } ``` ### Reference - WebSocketServer Class - Sfs2X.WebSocketSharp.Server Namespace ``` -------------------------------- ### Initialize Buddy List System Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/f5fd1dfa-f93e-41c3-0725-739c9c1faca4.htm Example showing how to register event listeners and send the InitBuddyListRequest to initialize the system. ```C# void SomeMethod() { sfs.AddEventListener(SFSBuddyEvent.BUDDY_LIST_INIT, OnBuddyInited); sfs.AddEventListener(SFSBuddyEvent.BUDDY_ERROR, OnBuddyError); // Initialize the Buddy List system sfs.Send(new InitBuddyListRequest()); } void OnBuddyInited(BaseEvent evt) { Console.WriteLine("Buddy List system initialized successfully"); // .Net / Unity System.Diagnostics.Debug.WriteLine("Buddy List system initialized successfully"); // UWP // Retrieve my buddies list List buddies = sfs.BuddyManager.BuddyList; // Display the online buddies in a list component in the application interface ... } void OnBuddyError(BaseEvent evt) { Console.WriteLine("The following error occurred while executing a buddy-related request: " + (string)evt.Params["errorMessage"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("The following error occurred while executing a buddy-related request: " + (string)evt.Params["errorMessage"]); // UWP } ``` -------------------------------- ### Get WebSocket Handshake Request Context Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/67dc13c3-5da8-5f37-8185-58396b7d9b9b.htm Access the WebSocketContext to retrieve information from a WebSocket handshake request. Returns null if the session has not yet started. ```csharp public WebSocketContext Context { get; } ``` -------------------------------- ### Initialize Buddy List System Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/InitBuddyListRequest.html This example demonstrates how to initialize the Buddy List system. It includes setting up event listeners for successful initialization and errors, and then sending the InitBuddyListRequest. Ensure this is the first operation when using Buddy List features. ```javascript function someMethod() { sfs.addEventListener(SFS2X.SFSBuddyEvent.BUDDY_LIST_INIT, onBuddyListInitialized, this); sfs.addEventListener(SFS2X.SFSBuddyEvent.BUDDY_ERROR, onBuddyError, this) // Initialize the Buddy List system sfs.send(new SFS2X.InitBuddyListRequest()); } ``` ```javascript function onBuddyListInitialized(evtParams) { console.log("Buddy List system initialized successfully"); // Retrieve my buddies list var buddies = sfs.buddyManager.getBuddyList(); // Display the online buddies in a list component in the application interface ... } ``` ```javascript function onBuddyError(evtParams) { console.log("The following error occurred while executing a buddy-related request: " + evtParams.errorMessage); } ``` -------------------------------- ### HttpServer.DocumentRootPath Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/d327d0c1-1382-831b-1e24-9390cba8c8fe.htm Gets or sets the path to the document folder of the server. The default value is './Public'. The set operation does nothing if the server has already started or is shutting down. ```csharp public string DocumentRootPath { get; set; } ``` -------------------------------- ### Connect to SmartFoxServer (JavaScript) Source: https://docs2x.smartfoxserver.com/ExtensionsJS/quick-start Initializes the SmartFox client, sets connection parameters, adds event listeners, and initiates the connection. Ensure the SFS2X library is included. ```javascript window.onload = function() { // Set connection parameters var config = {}; config.host = "127.0.0.1" config.port = 8080; config.zone = "BasicExamples"; // Create SmartFox client instance sfs = new SFS2X.SmartFox(config); // Add event listeners sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this); sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this); sfs.addEventListener(SFS2X.SFSEvent.LOGIN, onLogin, this); sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this); sfs.addEventListener(SFS2X.SFSEvent.EXTENSION_RESPONSE, onExtensionResponse, this); // Connect to SFS2X sfs.connect(); }; ``` -------------------------------- ### Tris (Tic-Tac-Toe) Game Example - iOS Source: https://docs2x.smartfoxserver.com/ExamplesIOS/tris This snippet demonstrates the Tris (Tic-Tac-Toe) game logic for iOS clients. It requires the SFS2X client API setup. ```objective-c #import "TrisGame.h" #import "TrisGameLogic.h" @implementation TrisGame - (id)init { if (self = [super init]) { _gameLogic = [[TrisGameLogic alloc] init]; } return self; } - (void)makeMove:(int)row col:(int)col player:(int)player { [_gameLogic makeMove:row col:col player:player]; } - (int)checkWinner { return [_gameLogic checkWinner]; } - (BOOL)isBoardFull { return [_gameLogic isBoardFull]; } - (void)resetGame { [_gameLogic resetGame]; } @end ``` -------------------------------- ### Initialize Game Scene Controller Source: https://docs2x.smartfoxserver.com/ExamplesUnity/mmo-basics Sets up the SmartFox client reference, event listeners, player avatar, and Area of Interest visualization in the Start method. ```C# private void Start() { // Set a reference to the SmartFox client instance sfs = gm.GetSfsClient(); // Hide modal panels HideModals(); // Add event listeners AddSmartFoxListeners(); // Set random model and material and spawn player model int numModel = UnityEngine.Random.Range(0, playerModels.Length); int numMaterial = UnityEngine.Random.Range(0, playerMaterials.Length); SpawnLocalPlayer(numModel, numMaterial); // Instantiate and set scale and position of game object representing the Area of Interest aoi = GameObject.Instantiate(aoiPrefab) as GameObject; Vec3D aoiSize = ((MMORoom)sfs.LastJoinedRoom).DefaultAOI; aoi.transform.localScale = new Vector3(aoiSize.FloatX * 2, 10, aoiSize.FloatZ * 2); aoi.transform.position = new Vector3(localPlayer.transform.position.x, -3, localPlayer.transform.position.z); // Update settings panel with the selected model and material settingsPanel.SetModelSelection(numModel); settingsPanel.SetMaterialSelection(numMaterial); } ``` -------------------------------- ### Get Request Trace Identifier (C#) Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/460f76e1-eb4d-ae60-3940-1e36a6e974c9.htm Access the RequestTraceIdentifier property to obtain a Guid representing the unique trace identifier for an incoming HTTP request. This property is read-only. ```csharp public Guid RequestTraceIdentifier { get; } ``` -------------------------------- ### Get Spawn Points (Java) Source: https://docs2x.smartfoxserver.com/ExamplesUnity/shooter Defines and returns an array of Transform objects representing spawn points for characters and items. This method is used to configure game start positions. ```Java private static Transform[] getSpawnPoints() { Transform[] spawnPoints = new Transform[8]; spawnPoints[0] = new Transform(-30.0D, 1.0D, 22.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[1] = new Transform(13.0D, 1.0D, 27.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[2] = new Transform(1.0D, 1.0D, -17.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[3] = new Transform(1.0D, 1.0D, 8.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[4] = new Transform(6.0D, 1.0D, 47.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[5] = new Transform(-5.0D, 1.0D, 47.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[6] = new Transform(0.0D, 1.0D, 24.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); spawnPoints[7] = new Transform(0.0D, 1.0D, 37.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); return spawnPoints; } ``` -------------------------------- ### Add Buddy Example Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/61172c64-f11c-a25a-a6db-163aff48cfa3.htm Demonstrates how to send a request to add a buddy. Ensure the Buddy List system is initialized and event listeners for BUDDY_ADD and BUDDY_ERROR are set up. ```csharp void SomeMethod() { sfs.AddEventListener(SFSBuddyEvent.BUDDY_ADD, OnBuddyAdded); sfs.AddEventListener(SFSBuddyEvent.BUDDY_ERROR, OnBuddyError); // Add Jack as a new buddy to my buddies list sfs.Send(new AddBuddyRequest("Jack")); } ``` ```csharp void OnBuddyAdded(BaseEvent evt) { Console.WriteLine("Buddy was added: " + (Buddy)evt.Params["buddy"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("Buddy was added: " + (Buddy)evt.Params["buddy"])); // UWP } ``` ```csharp void OnBuddyError(BaseEvent evt) { Console.WriteLine("The following error occurred while executing a buddy-related request: " + (string)evt.Params["errorMessage"]); // .Net / Unity System.Diagnostics.Debug.WriteLine("The following error occurred while executing a buddy-related request: " + (string)evt.Params["errorMessage"]); // UWP } ``` -------------------------------- ### Initialize SmartFoxServer Connection Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/index.html This example demonstrates how to create an instance of the main SmartFox class, add event listeners for connection events, and establish a connection to SmartFoxServer. The onConnection function handles success or failure. ```javascript var sfs = new SFS2X.SmartFox(); sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this); sfs.connect(127.0.0.1, 8080); function onConnection(evtParams) { if (evtParams.success) console.log("Connected to SmartFoxServer 2X!"); else console.log("Connection failed. Is the server running at all?"); } ``` -------------------------------- ### Get Room Count - C# Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/538c900b-23d1-5099-cd01-8e007f5f4cb0.htm Use this method to retrieve the total number of rooms available in the server's room list. No specific setup is required beyond having an instance of SFSRoomManager. ```csharp public int GetRoomCount() ``` -------------------------------- ### Create a New Chat Room Source: https://docs2x.smartfoxserver.com/api-docs/jsdoc/client/SFSEvent.html This example shows how to create a new chat room with specified settings and handle room creation events. It requires setting up listeners for both successful creation and errors. ```javascript function someMethod() { sfs.addEventListener(SFS2X.SFSEvent.ROOM_ADD, onRoomCreated, this); sfs.addEventListener(SFS2X.SFSEvent.ROOM_CREATION_ERROR, onRoomCreationError, this); // Define the settings of a new chat Room var settings = new SFS2X.RoomSettings("My Chat Room"); settings.maxUsers = 40; settings.groupId = "chats"; // Create the Room sfs.send(new SFS2X.CreateRoomRequest(settings)); } function onRoomCreated(evtParams) { console.log("Room created: " + evtParams.room); } function onRoomCreationError(evtParams) { console.log("Room creation failure: " + evtParams.errorMessage); } ``` -------------------------------- ### WebSocketServiceHost.WaitTime Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/59606e0a-b6e8-8778-9d12-7911ae063a77.htm Gets or sets the time to wait for the response to the WebSocket Ping or Close. The set operation does nothing if the service has already started or is shutting down. An ArgumentOutOfRangeException is thrown if the value is zero or less. ```csharp public TimeSpan WaitTime { get; set; } ``` -------------------------------- ### Game Rooms and Matchmaking Example (Unity C#) Source: https://docs2x.smartfoxserver.com/ExamplesUnity/introduction Demonstrates setting up game rooms and implementing matchmaking logic. This is crucial for connecting players for multiplayer games. ```csharp using UnityEngine; using Sfs2X.Core; using Sfs2X.Requests; public class MatchmakingExample : MonoBehaviour { private SmartFox sfs; void Start() { sfs = new SmartFox(true); sfs.AddEventListener(SFSEvent.CONNECTION_SUCCESS, OnConnectionSuccess); sfs.AddEventListener(SFSEvent.LOGIN, OnLogin); sfs.AddEventListener(SFSEvent.MATCH_MAKER_COMPўцаў, OnMatchmakerCompўцаў); sfs.Connect("127.0.0.1", 9933); } void OnConnectionSuccess(BaseEvent evt) { sfs.Send(new LoginRequest("User", "", "MyZone")); } void OnLogin(BaseEvent evt) { // Join the matchmaker queue sfs.Send(new JoinMatchmakerQueueRequest("default", "1.0")); } void OnMatchmakerCompўцаў(BaseEvent evt) { Debug.Log("Matchmaker found a game!"); // The event parameters will contain details about the new game room } } ``` -------------------------------- ### HttpServer.Realm Property C# Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/3db3db7a-2283-3b27-4d87-4ba5affdcca0.htm Gets or sets the realm used for authentication. The default realm is 'SECRET AREA' if the value is null or empty. Setting this property has no effect if the server has already started or is shutting down. ```csharp public string Realm { get; set; } ``` -------------------------------- ### SignUpAssistantComponent Initialization and Configuration Source: https://docs2x.smartfoxserver.com/api-docs/javadoc/server/com/smartfoxserver/v2/components/signup/SignUpAssistantComponent.html This snippet demonstrates how to initialize and configure the SignUpAssistantComponent within an SFSExtension. It shows setting up the sign-up table, extra fields, and email response parameters. ```APIDOC ## SFSExtension with SignUpAssistantComponent ### Description This example shows a basic `SFSExtension` that utilizes the `SignUpAssistantComponent` to set up a user sign-up process. It configures the component with a specific database table, custom fields, and email notification settings. ### Initialization (`init` method) ```java public class SignUpTestExtension extends SFSExtension { private SignUpAssistantComponent suac; public void init() { suac = new SignUpAssistantComponent(); // Configure sign-up table suac.getConfig().signUpTable = "signup_test"; // Configure extra fields for the sign-up form suac.getConfig().extraFields = Arrays.asList("country", "age", "zone"); // Configure email response for sign-up confirmation suac.getConfig().emailResponse.isActive = true; suac.getConfig().emailResponse.fromAddress = "info@mywebsite.com"; suac.getConfig().emailResponse.subject = "Thanks for signing up"; suac.getConfig().emailResponse.template = "SignUpEmailTemplates/SignUpConfirmation.html"; // Add the SignUpAssistantComponent as a request handler addRequestHandler(SignUpAssistantComponent.COMMAND_PREFIX, suac); } public void destroy() { super.destroy(); } } ``` ### Component Details #### SignUpAssistantComponent ##### Field Summary - `static java.lang.String COMMAND_PREFIX`: Represents the command prefix for handling requests. ##### Constructor Summary - `SignUpAssistantComponent()`: Initializes a new instance of the component. ##### Method Summary - `SignUpConfiguration getConfig()`: Retrieves the configuration object for the component. - `IDBManager getDbManager()`: Retrieves the database manager. - `void handleClientRequest(User sender, ISFSObject params)`: Handles incoming client requests. ### Configuration (`SignUpConfiguration`) #### Fields - `signUpTable` (String): The name of the database table used for storing sign-up information. - `extraFields` (List): A list of additional fields to include in the sign-up process. - `emailResponse` (EmailResponseConfig): Configuration for email notifications. ##### `EmailResponseConfig` Fields - `isActive` (boolean): Enables or disables email responses. - `fromAddress` (String): The sender's email address. - `subject` (String): The subject line of the email. - `template` (String): The path to the email template file. ### Request Handling #### `handleClientRequest` Method ##### Parameters - `sender` (User): The user who sent the request. - `params` (ISFSObject): The parameters of the request. ### Version Information - **Since**: 2.7.0 ### Related Components - `SignUpConfiguration` ``` -------------------------------- ### WebSocketServer.Realm Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/d62430af-2ba9-72a4-ab1b-296902345a73.htm Gets or sets the realm used for authentication. The realm is a string that identifies a security domain. If null or empty, 'SECRET AREA' is used. The set operation is ignored if the server has already started or is shutting down. ```APIDOC ## WebSocketServer.Realm Property ### Description Gets or sets the realm used for authentication. ### Method GET, SET ### Endpoint N/A (This is a class property) ### Parameters #### Property Value - **Realm** (String) - Gets or sets the realm used for authentication. - Type: String - Description: A String or null by default. That string represents the name of the realm. "SECRET AREA" is used as the realm if the value is null or an empty string. The set operation does nothing if the server has already started or it is shutting down. ### Request Example ```csharp // Setting the realm webSocketServer.Realm = "MyCustomRealm"; // Getting the realm string currentRealm = webSocketServer.Realm; ``` ### Response #### Success Response (200) - **Realm** (String) - The current realm value. #### Response Example ```json { "Realm": "MyCustomRealm" } ``` ### Reference - WebSocketServer Class - Sfs2X.WebSocketSharp.Server Namespace ``` -------------------------------- ### Implement SignUpAssistantComponent in an Extension Source: https://docs2x.smartfoxserver.com/api-docs/javadoc/server/com/smartfoxserver/v2/components/signup/SignUpAssistantComponent.html Demonstrates initializing the SignUpAssistantComponent within an SFSExtension to handle sign-up requests with custom database and email configurations. ```java public class SignUpTestExtension extends SFSExtension { private SignUpAssistantComponent suac; public void init() { suac = new SignUpAssistantComponent(); suac.getConfig().signUpTable = "signup_test"; suac.getConfig().extraFields = Arrays.asList("country", "age", "zone"); suac.getConfig().emailResponse.isActive = true; suac.getConfig().emailResponse.fromAddress = "info@mywebsite.com"; suac.getConfig().emailResponse.subject = "Thanks for signing up"; suac.getConfig().emailResponse.template = "SignUpEmailTemplates/SignUpConfirmation.html"; addRequestHandler(SignUpAssistantComponent.COMMAND_PREFIX, suac); } public void destroy() { super.destroy(); } } ``` -------------------------------- ### Get SFSBuddy State Property C# Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/5f664ed8-cc25-2b18-7100-61f2364c201a.htm Use this property to retrieve the custom state of a buddy. If no custom state is set, it returns null. Examples of custom states include 'Available', 'Busy', or 'Be right back'. ```csharp public string State { get; } ``` -------------------------------- ### Bootstrap Boost.Asio Source: https://docs2x.smartfoxserver.com/GettingStarted/client-api-cpp-windows-eclipse Run the bootstrap script for Boost.Asio, specifying the installation prefix. This prepares the Boost.Asio libraries for compilation. ```bash ./bootstrap.sh –prefix=boost/ ``` -------------------------------- ### WebSocketServer.AllowForwardedRequest Property Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/9bc13124-7012-d219-34d5-009f9a67031f.htm Gets or sets a value indicating whether the server accepts every handshake request without checking the request URI. The default value is false. The set operation does nothing if the server has already started or it is shutting down. ```csharp public bool AllowForwardedRequest { get; set; } ``` -------------------------------- ### QuickJoinGameRequest Constructor (MatchExpression, List, Room) Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/5695b5c3-e696-3f0b-d1f3-184f261c4452.htm Use this constructor to create a request to join a game room. It requires a matching expression, a list of group names to search within, and an optional room to leave. The instance must be sent via SmartFox.Send. ```csharp public QuickJoinGameRequest( MatchExpression matchExpression, List whereToSearch, Room roomToLeave ) ``` -------------------------------- ### Install SmartFoxServer API via NPM Source: https://docs2x.smartfoxserver.com/GettingStarted/client-api-html5 Execute this command in the project's main folder to add the API as a dependency. ```bash > npm install sfs2x-api --save ``` -------------------------------- ### WebSocketServer ReuseAddress Property C# Source: https://docs2x.smartfoxserver.com/api-docs/csharp-doc/html/d166617d-68fe-89f1-7050-fa3d3242f32a.htm Gets or sets a value indicating whether the server is allowed to be bound to an address that is already in use. Set to true to resolve TIME_WAIT states. The set operation does nothing if the server has already started or is shutting down. ```csharp public bool ReuseAddress { get; set; } ``` -------------------------------- ### Install g++ on Ubuntu Source: https://docs2x.smartfoxserver.com/GettingStarted/client-api-cpp-linux-eclipse Use this command to install the g++ compiler on Ubuntu systems. Ensure you have build-essential installed. ```bash $ sudo apt-get install build-essential g++ ``` -------------------------------- ### Establish a Standard Connection in Unity Source: https://docs2x.smartfoxserver.com/GettingStarted/cryptography Demonstrates initializing a SmartFox client, configuring connection data, and handling the connection and cryptography handshake events. ```csharp public class ConnectionExample : MonoBehaviour { private SmartFox sfs; // Use a flag to easily switch cryptography on and off private bool useEncryption = true; void Start() { // Create the SmartFox client instance sfs = new SmartFox(); // Add event listeners sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection); sfs.AddEventListener(SFSEvent.CRYPTO_INIT, OnCryptoInit); sfs.AddEventListener(SFSEvent.LOGIN, OnLogin); // Create configuration object ConfigData config = new ConfigData(); config.host = "mydomain.com"; config.port = 9933; config.zone = "BasicExamples"; // Connect sfs.Connect(config); } // Send a login request private void DoLogin() { sfs.Send(new LoginRequest("Fozzie")); } // Handle connection event private void OnConnection(BaseEvent evt) { if ((bool)evt.Params["success"]) { // Initialize protocol cryptography if needed, otherwise send a login request if (useEncryption) sfs.InitCrypto(); else DoLogin(); } } // Handle encryption initialization event private void OnCryptoInit(BaseEvent evt) { if ((bool) evt.Params["success"]) { // Send a login request DoLogin(); } } // Handle login event private void OnLogin(BaseEvent evt) { Debug.Log("Logged in"); } } ```