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

 

» Connector

» Overview

The Connector example is the most basic application you can create: its sole purpose is to connect to SmartFoxServer 2X using the Android 2.2 emulator.

Once the application is launched, the user is prompted to enter the SmartFoxServer 2X connection details.
The connection parameters used in this example are the server's IP address to connect to and the TCP port used for communication. The default values used by the app are 10.0.2.2, which is an alias specifically setup in the Android emulator to contact your localhost 127.0.0.1, and port 9933.

After the details are submitted, a connection to SmartFoxServer 2X is attempted.An event is then fired to notify if the connection has been established or not.

On successful connection to SmartFoxServer 2X, notifications are written to a text area as events are received, making it easy to trace the series of events.

>> DOWNLOAD the source files <<

» Installation

In order to access the application's source code and run it in the Android Virtual Device (emulator), follow these steps:

  1. Make sure your SmartFoxServer 2X installation contains the BasicExamples Zone definition;
  2. Start SmartFoxServer 2X;
  3. In Eclipse, import the Android project contained in the /source folder from the download above;
  4. Launch the app and change the connection details if your SmartFoxServer 2X is not installed on your machine's localhost.

» Code highlights

Note: For clarity purposes the calls to the Android’s Log has been removed in the following chunks of code.

We will use the currentStatus flag to hold the current status of the connection with the server. The possible values are

	private enum Status {
		DISCONNECTED, CONNECTED, CONNECTING, CONNECTION_ERROR, CONNECTION_LOST, LOGGED, IN_A_ROOM
	}

The onCreate method is called by the system when the Activity is first created. Here we setup the UI for the app and initialize the SmartFoxServer 2X client.

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_connector);
		System.setProperty("java.net.preferIPv6Addresses", "false");
		initSmartFox();
		initUI();
		setStatus(Status.DISCONNECTED);
	}

The following line:

	System.setProperty("java.net.preferIPv6Addresses","false");

is included as the emulator does not support IPv6.

In the initSmartFox method, we instantiate the SmartFoxServer 2X client, which handles communication between the device and the server. As this class is also responsible for handling events being dispatched by the server, we also have to set up the appropriate event listeners.

	private void initSmartFox() {
		// Instantiate SmartFox client
		sfsClient = new SmartFox(DEBUG_SFS);
		// Add event listeners
		sfsClient.addEventListener(SFSEvent.CONNECTION, this);
		sfsClient.addEventListener(SFSEvent.CONNECTION_LOST, this);
		sfsClient.addEventListener(SFSEvent.LOGIN, this);
		sfsClient.addEventListener(SFSEvent.LOGIN_ERROR, this);
		sfsClient.addEventListener(SFSEvent.ROOM_JOIN, this);
		sfsClient.addEventListener(SFSEvent.HANDSHAKE, this);
		sfsClient.addEventListener(SFSEvent.SOCKET_ERROR, this);
	}

In the initUIinitUI method, we initialize the references to the Views and their events listeners (onClickListeners, onCheckedChangeListener, etc.).

Finally we set the initial status to DISCONNECTED.

To connect the client to the server we use the following code:

	private void connect(String serverIP, String serverPort) {
		// if the user have entered port number it uses it...
		if (serverPort.length() > 0) {
			int serverPortValue = Integer.parseInt(serverPort); serverPort);
			sfsClient.connect(serverIP, serverPortValue);
		}
		// ...otherwise uses the default port number
		else {
			sfsClient.connect(serverIP);
		}
	}

Since all the calls to the SmartFox object (sfsClient) are asynchronous we can call it in the application’s main thread.

Events fired from the server are handled in the code below. When the CONNECTION event is dispatched by the server, we handle it by checking the success parameter of the event object. If the connection was successful, the currentStatus flag is set to CONNECTED and a request is sent to log in to the zone that is defined in the project's strings.xml.

	@Override
	public void dispatch(final BaseEvent event) throws SFSException {
		if (event.getType().equalsIgnoreCase(SFSEvent.CONNECTION)) {
			if (event.getArguments().get("success").equals(true)) {
				// Login as guest in current zone
				sfsClient.send(new LoginRequest("", "", getString(R.string.example_zone)));
				setStatus(Status.CONNECTED, sfsClient.getConnectionMode());
			} else {
				setStatus(Status.CONNECTION_ERROR);
			}
		} else if (event.getType().equalsIgnoreCase(SFSEvent.CONNECTION_LOST)) {
			setStatus(Status.CONNECTION_LOST);
			disconnect();
		} else if (event.getType().equalsIgnoreCase(SFSEvent.LOGIN)) {
			setStatus(Status.LOGGED, sfsClient.getCurrentZone());
			sfsClient.send(new JoinRoomRequest(getString(R.string.example_lobby)));
		} else if (event.getType().equalsIgnoreCase(SFSEvent.ROOM_JOIN)) {
			setStatus(Status.IN_A_ROOM, sfsClient.getLastJoinedRoom().getName());
		}
	}

When the client logs in the event LOGIN is dispatched, then the currentStatus flag is set to LOGGED and a request to join to the room “The Lobby” is sent.

Then a ROOM_JOIN event is received to confirm the connection to the room.

The setStatus method just sets currentStatus to the new value, updates the message at the bottom of the screen and adds a message to the log.

Note that it is important to free the resources in order to avoid memory leaks, so we override the Activity’s onDestroy method to disconnect (if needed), and remove the event listeners.

	/**
	 * Frees the resources.
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		disconnect();
		sfsClient.removeAllEventListeners();
	}
	
	/**
	 * Disconnect the client from the server
	 */
	private void disconnect() {
		if (sfsClient.isConnected()) {
			sfsClient.disconnect();
		}
	}

You can now proceed with more advanced examples showing real applications and games.

» More resources

You can learn more about the SmartFoxServer basics by consulting the following resources: