SFS2X Docs / ExamplesJS / connector
» Connector
» Overview
The Connector example is the most simple application you can create: it just shows how to set the client configuration and connect to SmartFoxServer 2X.
The SmartFoxServer 2X client API allows the connection details to be set in a configuration object passed to the main API class (SmartFox) constructor. The basic connection parameters set in this object are the server's address to connect to and the WebSocket port used for communication. For a detailed list of available parameters, please refer to the JavaScript client API documentation.
After the client configuration is passed, the connection can be attempted. An event is then fired to notify if the connection has been established successfully or not.
This simple example features a single button which causes, when pushed, the configuration to be set and the connection to the SmartFoxServer 2X instance to be established. The area on the right displays some information when events are received, making it clear what is going on.
>> DOWNLOAD the source files <<
» Running the example
In order to run the example, follow these steps:
- start SmartFoxServer 2X (v2.13 or later is required);
- make sure WS protocol is enabled in SFS2X configuration (read Server setup in the intro);
- open the /index.html file in a browser (Firefox recommended).
» Code highlights
The Connector interface is defined in the main html file, which also links both the SmartFoxServer API library and the external JavaScript file containing the example logic:
<head> ... <script type="text/javascript" src="libs/sfs2x-api-1.7.11.js"></script> <script type="text/javascript" src="scripts/main.js"></script> </head>
» Establishing a connection
When the Connect button is clicked, the onConnectBtClick function takes care of initializing the main SmartFoxServer client API class and establishing the connection to the server.
function onConnectBtClick() { // Clear log window document.getElementById("log").innerHTML = ""; // Disable interface enableInterface(false); // Log message trace("Connecting..."); // Create configuration object var config = {}; config.host = document.getElementById("addressIn").value; config.port = Number(document.getElementById("portIn").value); config.debug = document.getElementById("debugCb").checked; config.useSSL = false; // Create SmartFox client instance sfs = new SFS2X.SmartFox(config); // Set logging sfs.logger.level = SFS2X.LogLevel.DEBUG; sfs.logger.enableConsoleOutput = true; sfs.logger.enableEventDispatching = true; sfs.logger.addEventListener(SFS2X.LoggerEvent.DEBUG, onDebugLogged, this); sfs.logger.addEventListener(SFS2X.LoggerEvent.INFO, onInfoLogged, this); sfs.logger.addEventListener(SFS2X.LoggerEvent.WARNING, onWarningLogged, this); sfs.logger.addEventListener(SFS2X.LoggerEvent.ERROR, onErrorLogged, this); // Add event listeners sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this); sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this); // Attempt connection sfs.connect(); }
First of all, a configuration object is created (using the server address and port set by the user) and passed to a new SmartFox class instance, which is responsible of the whole communication between the client and the server.
Then the logging is configured, to be able to show the internal SFS debug messages (typically outgoing requests and incoming responses) in the application interface. In a common use case scenario this is not needed, because the same messages can be read in the browser's JavaScript console, but this approach (using an hidden panel for example) can still be useful in mobile development (where a console is usually not available).
As the SmartFox class is also responsible of dispatching the events coming from the server, we also have to setup the listeners (in this case just a couple, being the example very basic) so that our code can "react" appropriately. In particular notice that a scope is also passed together with the listener functions.
The last action is to make the client connect to the server. As no parameters are passed to the SmartFox.connect() method, the settings object passed to the constructor will be used.
» Handling SmartFoxServer events
In this example we register the handlers for the two primary events fired by the API, related to connection and disconnection. Basically, when the client gets connected to the server, the onConnection() method is executed; when it gets disconnected (for whatever reason), the onConnectionLost() method is called.
The four log event listeners show the inner informations logged by the API as mentioned before (provided that the "Show debug" checkbox in the user interface is checked — see the initial configuration object).
All event listeners have the same signature, with a single object being received. This contains all event specific parameters that developers might need in that context. Which parameters are provided by what events is documented in the SFSEvent class documentation.
CONNECTION event handler
The onConnection() method is called when the API completes the connection process (whether successfully or not). The event parameter is the "success" boolean.
function onConnection(event) { if (event.success) { trace("Connected to SmartFoxServer 2X!<br>SFS2X API version: " + sfs.version); // Show disconnect button switchButtons(); } else { trace("Connection failed: " + (event.errorMessage ? event.errorMessage + " (" + event.errorCode + ")" : "Is the server running at all?")); // Reset reset(); } }
If the connection is successful, some details are printed to the interface's log panel (most recent message at the top) and the visibility of Connect and Disconnect buttons is switched.
If the connection failed and a specific error message is provided, then this is printed in the log (otherwise a generic message is printed). Also, a reset is performed, as further described next.
CONNECTION_LOST event handler
The onConnectionLost() method is called when the client looses the connection. The disconnection reason is contained in a string in the event's parameters.
function onConnectionLost(event) { trace("Disconnection occurred; reason is: " + event.reason); // Hide disconnect button switchButtons(); // Reset reset(); } function reset() { // Enable interface enableInterface(true); // Remove SFS2X listeners sfs.removeEventListener(SFS2X.SFSEvent.CONNECTION, onConnection); sfs.removeEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost); sfs.logger.removeEventListener(SFS2X.LoggerEvent.DEBUG, onDebugLogged); sfs.logger.removeEventListener(SFS2X.LoggerEvent.INFO, onInfoLogged); sfs.logger.removeEventListener(SFS2X.LoggerEvent.WARNING, onWarningLogged); sfs.logger.removeEventListener(SFS2X.LoggerEvent.ERROR, onErrorLogged); sfs = null; }
In this example, which just makes the connection to the server, this method is called if the idle time configured on the server is exceeded, if the physical connection with the server is interrupted (for example stopping SmartFoxServer) or if the Disconnect button is clicked.
When the disconnection occurs (for any reason), all the listeners added to the SmartFox instance are removed and the reference to that instance (sfs) is set to null. This makes the example return to the initial state, and we can start another connection.
Log event handlers
The SmartFoxServer client API features an internal logger used to debug the messages exchanged between the client and the server and report other internal informations. The logger uses four "levels", which can be set using the SmartFox.logger.level property:
- DEBUG — very low-level internal API debug informations; it can be useful to check the messages a game sends to and receives from SmartFoxServer, including their binary content
- INFO — standard internal API debug informations; this is the default level to which the Logger is set and can be useful to see what requests/responses are sent/received (without their content)
- WARN and ERROR — internal API warnings and errors; they can be useful to know if you are doing something wrong with the API in your game
The example registers the listeners for all the levels: each method prints the message both in the browser's console and in the log panel in the example's UI.
To see more advanced uses of SmartFoxServer you can now move onwards to the next examples.
NOTE
You should also read the comments to methods and properties in the example source code for additional informations.
» More resources
You can learn more about the SmartFoxServer basics by consulting the following resources:
- Development basics (introduction to the Zone concept and basic client-server communication steps)
- The connection phase (server connection basics)