SFS2X and Node.js

Some time ago we have been asked by the developers at Gameshastra how to integrate our SFS2X JavaScript client API in Node.js, in order to create a Node application capable of interacting with SmartFoxServer 2X.

We have a strategy game for which we built native client apps in Android, iOS and HTML5. We are also exposing the client functionality as a rest api for apps to be built for Amazon Alexa and Google Assistant. That rest api is being built on Node.js and we want to consume the same services hosted on SFS2X, so that we can manage all the platforms from the same server base and provide unified experience.


At the time, the bundling system we used to generate our API library caused some compatibility issues with Node, so we had to rethink the whole process. Today, after the release of v1.7.10 of the API, compatibility is fully guaranteed and integration is very easy to achieve.

In this post we are going to show how to connect to SmartFoxServer and handle the very basic connection and disconnection events. We will use the npm package manager to install the required libraries (including our JS API), so we assume that you have it installed (together with Node, of course) and that you have a basic knowledge of this tool.

Setup

Create a new folder called, for example, sfs-connect. Open it in a console window of your operating system and run the npm’s init command to generate a new package.json file. You can keep the default settings suggested by the initialization process.

npm init

It is now time to install the required dependencies.

First of all, Node.js doesn’t support the websocket protocol out-of-the-box (like browsers). This is mandatory to connect to SmartFoxServer, so you need to look for a specific library. The ws: a Node.js WebSocket library package works just fine. You can install it with npm’s install command:

npm install ws --save

Now you need the actual SFS2X JavaScript API. We provide an official npm package which you can install with the following command:

npm install sfs2x-api --save

The –save flag adds the libraries to the dependencies section of the package.json file, which should now look like this:

{
  "name": "node-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "sfs2x-api": "^1.7.10-a",
    "ws": "^5.1.1"
  }
}

You are now ready to write the actual JavaScript code of a simple application.

Connection code

Create the index.js file in the project’s folder and past the code below:

// Load libraries
WebSocket = require("ws"); // https://www.npmjs.com/package/ws
SFS2X = require("sfs2x-api"); // https://www.npmjs.com/package/sfs2x-api

//------------------------------------------------------------------------------

// Create configuration object
var config = {};
config.host = "localhost";
config.port = 8080;
config.debug = true;
config.useSSL = false;

// Create SmartFox client instance
let sfs = new SFS2X.SmartFox(config);

// Add connection event listeners
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this);

// Connect to SmartFoxServer
sfs.connect();

//------------------------------------------------------------------------------

// Connection event handler
function onConnection(event)
{
	if (event.success)
	{
		console.log("Connected to SmartFoxServer 2X!");
		console.log("SFS2X API version: " + sfs.version);
	}
	else
		console.warn("Connection failed: " + (event.errorMessage ? event.errorMessage + " (" + event.errorCode + ")" : "Is the server running at all?"));
}

// Disconnection event handler
function onConnectionLost(event)
{
	console.warn("Disconnection occurred; reason is: " + event.reason);
}

The initial section of the code loads the required libraries using CommonJS require syntax. This makes the WebSocket object available to the SFS2X API and the SFS2X namespace available to your code.

In the next code section, the connection with SmartFoxServer is actually attempted after instantiating the SmartFox class. This requires a configuration object and listener to be attached to make our code react to the connection and disconnection events fired by the server.

This example of course only scratches the surface of the interaction with SmartFoxServer, but it should help you to get started in developing a multiplayer application in Node.js.

A big thank you to Gopal at Gameshastra for his feedback and help in refining our JS API.