Examples (iOS)
Examples (Android)

 

» 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

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
public void onCreate(Bundle savedInstanceState)
{
	super.onCreate(savedInstanceState);
	System.setProperty("java.net.preferIPv6Addresses", "false");
	setContentView(R.layout.main);

	myTextView = (TextView) this.findViewById(R.id.status);
	initSmartFox();
}

The 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. Finally we display the dialog box to accept user input for the connection parameters.

private void initSmartFox()
{
	// Instantiate SmartFox client
	sfsClient = new SmartFox(true);

	// Add event listeners
	sfsClient.addEventListener(SFSEvent.CONNECTION, this);
	sfsClient.addEventListener(SFSEvent.CONNECTION_LOST, this);
	sfsClient.addEventListener(SFSEvent.LOGIN, this);
	sfsClient.addEventListener(SFSEvent.ROOM_JOIN, this);
	sfsClient.addEventListener(SFSEvent.HANDSHAKE, this);


	// Displays the connect dialog box so the user can enter the server IP and port.
	showDialog(DIALOG_CONNECT_ID);
}

The following code overrides the Activity's onCreateDialog callback method to display the relevant dialog window to the user.

@Override
/**
 * Callback for creating dialogs that are managed by the activity.
 */
protected Dialog onCreateDialog(int id)
{
	switch(id)
	{
		case DIALOG_CONNECT_ID:
			return getConnectDialog();
		
		...
		
		default:
				return super.onCreateDialog(id);
	}
}

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 we remove the dialog and send a request to log in to the zone that is defined in the project's strings.xml file.

/**
 * Handle events dispatched from the SFS2X server
 * @param event - the event that has been dispatched from the server
 *
 * @throws SFSException
 */
@Override
public void dispatch(final BaseEvent event) throws SFSException
{
	runOnUiThread(new Runnable() {
		public void run() {
			if(event.getType().equalsIgnoreCase(SFSEvent.CONNECTION))
			{
				status = getString(R.string.connected);
				handler.sendEmptyMessage(0);
				if(event.getArguments().get("success").equals(true))
				{
					// Login as guest in current zone
					sfsClient.send(new LoginRequest("", "", getString(R.string.zone)));
					removeDialog(DIALOG_CONNECTING_ID);
				}
				//otherwise error message is shown
				else
				{
					removeDialog(DIALOG_CONNECTING_ID);
					showDialog(DIALOG_CONNECTION_ERROR_ID);
				}
			}
			.
			.
			.
			else if(event.getType().equalsIgnoreCase(SFSEvent.ROOM_JOIN))
			{
				status = getString(R.string.roomJoin) + sfsClient.getLastJoinedRoom().getName() + "'.\n";
				handler.sendEmptyMessage(0);
			}
		}
	});
}

To connect the client to the server, a new thread is required. A separate thread is needed to allow the app's UI to run independantly.

/**
 * Connects to SmartFoxServer instance.
 *
 * @param ip the server IP.
 * @param port the server port.
 */
private void connectToServer(final String ip, final int port)
{
	showDialog(DIALOG_CONNECTING_ID);

	//connect() method is called in separate thread
	//so it does not blocks the UI
	final SmartFox sfs = sfsClient;
	new Thread() {
		@Override
		public void run() {
			sfs.connect(ip, port);
		}
	}.start();
}

Lastly, we must use a Handler object to pass messages between our threads. When we send a message to the Handler it is saved in a queue and is executed by the UI thread as soon as possible. The code below handles displaying text in the application's textView.

private Handler handler = new Handler()
{
	 public void handleMessage(Message msg)
	 {
		 myTextView.append(status);
	 }
};

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

» More resources

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