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

 

» Client API setup | Java

The Java API supports both standard Java applications and Android apps, using JDK 8 or higher.

The API is distributed as a number of JAR files including the main API and additional dependancies. They can easily be added to your Java project in the development IDE of yout choice.

If you don't know which Java IDE to choose we higly recommend two excellent and free products:

Adding the SFS2X API in Eclipse

After having created a new Java Project proceed with the following steps:

Adding the SFS2X API in IntelliJ IDEA

After having created a new Java Project proceed with the following steps:

Simple connection example

The following is a simple Java client example that connects to SmartFoxServer running on the local machine:

import sfs2x.client.*;
import sfs2x.client.requests.*;
import sfs2x.client.util.ConfigData;

public class SFS2XConnector
{
    SmartFox sfs;
    ConfigData cfg;

    public SFS2XConnector()
    {
        // Configure client connection settings
        cfg = new ConfigData();
        cfg.setHost("localhost");
        cfg.setPort(9933);
        cfg.setZone("BasicExamples");
        cfg.setDebug(false);

        // Set up event handlers
        sfs = new SmartFox();
        sfs.addEventListener(SFSEvent.CONNECTION, this::onConnection);
        sfs.addEventListener(SFSEvent.CONNECTION_LOST, this::onConnectionLost);
        sfs.addEventListener(SFSEvent.LOGIN, this::onLogin);
        sfs.addEventListener(SFSEvent.LOGIN_ERROR, this::onLoginError);

        System.out.println("API Ver: " + sfs.getVersion());
        // Connect to server
        sfs.connect(cfg);
    }

    // ----------------------------------------------------------------------
    // Event Handlers
    // ----------------------------------------------------------------------

    private void onConnection(BaseEvent evt)
    {
        boolean success = (boolean) evt.getArguments().get("success");

        if (success)
        {
            System.out.println("Connection success");
            sfs.send(new LoginRequest(""));
        }
        else
            System.out.println("Connection Failed. Is the server running?");

    }

    private void onConnectionLost(BaseEvent evt)
    {
        System.out.println("-- Connection lost --");
    }

    private void onLogin(BaseEvent evt)
    {
        System.out.println("Logged in as: " + sfs.getMySelf().getName());
    }

    private void onLoginError(BaseEvent evt)
    {
        String message = (String) evt.getArguments().get("errorMessage");
        System.out.println("Login failed. Error: " + message);
    }
}

 

« back to client API list