• Examples (iOS)
• Examples (Android)
• Examples (C++)
Server API Documentation


» Connector

» Overview

The Connector example simply shows how to setup and use the SmartFox client API object and how to establish a basic connection to the server. It also clearly shows how to deal with the different requirements of the Unity build targets, making use of a few conditional compilation statements.

The Unity scene mostly consists of a couple of world-space canvases representing the Connect panel, where to enter the parameters to connect to SmartFoxServer (host name or IP address and port), and the Debug panel, showing the client-server communication status.
This example features a single script component attached to the ConnectionPanel game object with the sole purpose to establish the connection to a SmartFoxServer 2X instance, as well as displaying the log messages from the API.

>> DOWNLOAD the source files <<

» Setup & run

In order to setup and run the example, follow these steps:

  1. make sure your SmartFoxServer 2X installation contains the BasicExamples Zone definition;
  2. start SmartFoxServer 2X (v2.13 or later is highly recommended);
  3. start Unity (v5.6 or later required);
  4. in the Projects panel click on the Open icon and browse to the /client/Connector folder, then click the Open button;
  5. wait for the project setup completion (Unity needs to regenerate some libraries);
  6. go to the Project panel, click on the Assets folder and double click on the MainScene scene to open it;
  7. click on the Play button to run the example in the Unity Editor, or go to the Build settings panel and build it for your target platform of choice.

All relevant assets are contained in the Assets/ConnectorAssets folder; in particular the C# code is in the Scripts subfolder and the SmartFoxServer 2X client API DLLs are in the Plugins subfolder. Read the introduction to understand why multiple DLLs are used.

» Code highlights

The code for this example is contained in the script file called Connector in the Scripts subfolder, attached to the ConnectionPanel game object in the scene.
The structure of the file is a basic Unity C# script with Start() and Update() methods. Additionally, there is a listener for the click event of the sole button in the UI, a few helper methods and some listeners for the SmartFoxServer client API events.

» Fields declaration

At the top of the script, where fields are declared, other than the UI components the script needs to interact with, there's a few private properties containing host and port values for the connection.

private string defaultHost = "";
private int defaultTcpPort = 9933;
private int defaultWsPort = 8080;

defaultHost, defaultTcpPort and defaultWsPort are used to pre-populate the host and port input fields in the UI depending on the target Unity build, so you don't have to figure out which port to type in when testing the example. More on this subject later on.
Of course all port values must match che corresponding settings in the server configuration.

The sfs field instead keeps a reference to the entry point of the SmartFoxServer C# client API, the SmartFox class. This is the main class used by the client to interact with the server through a set of requests and responses (under the form of events).

» Unity's Start callback

The Start() method just takes care of the interface initialization. This is where the UI input fields are pre-populated with the default values set in the fields declaration.

hostInput.text = defaultHost;

portInput.text = defaultTcpPort.ToString();
portInput.text = defaultWsPort.ToString();

The reason why we have two possible port numbers depends on the type of connection we want to establish with SmartFoxServer:

The proper port value is set using a bit of conditional compilation. For more informations please visit this page in the Unity documentation.

» Establishing a connection

The example UI features a single button used to connect to and disconnect from the server, depending on the connection status (checked using the SmartFox.IsConnected property). If not yet connected, the button starts a new connection, otherwise it disconnects the client from the server.

The initial part of the code performing the connection in the OnButtonClick() method (bound to the Button game object in the Unity Editor) takes care of negotiating a security policy with the server. It is important that this is done prior to any network activity in the application.
This applies to the WebPlayer build only, so the code is surrounded by a specific conditional compilation instruction.

if (!useEncryption) {
    if (!Security.PrefetchSocketPolicy(hostInput.text, Convert.ToInt32(portInput.text), 500)) {
        Debug.LogError("Security Exception. Policy file loading failed!");

The next relevant code section, after some UI updates, creates the SmartFox class instance and registers the event handlers required by the example. Additionally some log event listeners are added too.
Again, the example uses some conditional compilation to create the main API object. In fact, as mentioned before, Unity's WebGL build requires a websocket connection between the client and the server. A special constructor on the SmartFox object instructs the API to use this type of connection.

sfs = new SmartFox();
sfs = new SmartFox(UseWebSocket.WS_BIN);

If you are a bit familiar with Unity then the expression "event handler" should not sound new to you. In fact many of the built-in callback methods in Unity use events to handle situations that will occur at an undefined moment in the future. For example when two objects collide in your game, you have to implement the OnCollisionEnter event handler to have your code react to that particular collision event.

SmartFoxServer uses events quite a lot because you can receive messages at any time from the server or from other users. All you will have to do is write the appropriate functions to manage these different situations.

sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection);
sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);

sfs.AddLogListener(LogLevel.INFO, OnInfoMessage);
sfs.AddLogListener(LogLevel.WARN, OnWarnMessage);
sfs.AddLogListener(LogLevel.ERROR, OnErrorMessage);

We'll analyze the above event handlers while progressing in this tutorial, and more advanced handlers in other tutorials.

In the last part of the connection code, the configuration parameters required to establish a connection are set using the ConfigData object, which is then passed to the SmartFox.Connect() method, to actually start the connection process.

// Set connection parameters
ConfigData cfg = new ConfigData();
cfg.Host = hostInput.text;
cfg.Port = Convert.ToInt32(portInput.text);
cfg.Zone = "BasicExamples";
cfg.Debug = debugToggle.isOn;
// Connect to SFS2X

The code collects the data entered by the user in the example UI and performs the connection.
The mandatory parameters are the server's domain name or IP address (Host) and the connection port (Port).
As it regards the other settings instead:

» Handling SmartFoxServer events

For 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 in the Unity script component is executed; when it gets disconnected (for whatever reason), the OnConnectionLost() method is called.
The three log event listeners show the inner informations logged by the API instead (provided that the "Show debug" Toggle in the UI is checked).

Before discussing the handlers in detail, a fundamental note on thread safety: Unity is not thread safe. This means that the developer has to be careful not to e.g. manipulate arrays of strings while the Unity engine is accessing the same array for drawing the strings on the screen. This also is true for network events and the SmartFoxServer client API handles this by queuing events for later processing. This is controlled by the SmartFox.ThreadSafeMode property: if set to true (default in Unity), the events are queued and the handlers are called when the SmartFox.ProcessEvents() method is executed.
The following code is wrapped in the Unity's Update() callback, called when Unity is in a safe state to manipulate client data. Queued network events in the API are processed and all the relevant event handlers are called.

void Update() {
if (sfs != null)

When building for Windows Store, Unity generates a Visual Studio project which includes the SFS2X API contained in the Plugins/WindowsStore folder. As this is the API used in native Windows / Windows Phone development, by default the SmartFox.ThreadSafeMode property is set to false (while it is set to true in the other DLLs). This prevents the correct behavior of the example in Windows / Windows Phone, even if it works fine in the Editor and on the other platforms.
For this reason we have to set the value explicitly to true after creating the SmartFox instance.

All event callback methods have the same method signature with a single BaseEvent class as variable. It contains an Hashtable of event specific parameters that one can access. Which parameters are provided by what events is documented in the SFSEvent API documentation.

CONNECTION event handler

The OnConnection() method is called when the API completes the connection process (whether successfully or not). The event parameter is a "success" bool.

private void OnConnection(BaseEvent evt) {
    if ((bool)evt.Params["success"]) {
        trace("Connection established successfully");
        trace("SFS2X API version: " + sfs.Version);
        trace("Connection mode is: " + sfs.ConnectionMode);
        // Enable disconnect button
        button.interactable = true;
        buttonLabel.text = "DISCONNECT";
    } else {
        trace("Connection failed; is the server running at all?");
        // Remove SFS2X listeners and re-enable interface

If the connection is successful, some details are printed to the example's Debug panel (note that a WebGL build prints a different "connection mode" from the other Unity builds) and the button label is changed to "DISCONNECT".

CONNECTION LOST event handler

The OnConnectionLost() method is called when the client looses the connection. The reason is contained in a string in the event's parameters.

private void OnConnectionLost(BaseEvent evt) {
    trace("Connection was lost; reason is: " + (string)evt.Params["reason"]);
    // Remove SFS2X listeners and re-enable interface

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), the reset() method is called. This removes all the listeners added to the SmartFox instance before and sets the sfs property to null. This returns the example in the initial state, and we can start another connection. It is recommended not to reuse the SmartFox instance after a connection is lost: it is better (well, actually it is mandatory!) to create a new instance to avoid memory leaks; thus we have to remove the listeners from the old one, so it can be removed by the garbage collector.

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.LoggingLevel property:

The example registers three listeners for the INFO, WARN and ERROR levels: each method prints the message in the Unity console and in the Debug panel in the example's UI.

To see more advanced uses of SmartFoxServer you can now move onwards to the next examples.

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: