SFS2X Docs / ExamplesAndroid / simple-chat
» Simple Chat
» Overview
The Simple Chat example uses additional Android UI elements to build on the basic Connector example and shows how to distribute public messages in SmartFoxServer 2X using the Android 2.2 emulator.
Exchanging chat messages is the most basic functionality provided by SmartFoxServer 2X: users connected to the same Zone can send public messages to all the other users in the same Room, private messages to single users (regardless the Room they are in) and a different kind of private messages (called buddy messages) if the Buddy List system is enabled. Also, additional "super powers" are given to users being recognized as moderators or administrators.
The chat functionalities provided by SmartFoxServer 2X can be the core of a fully featured chat website/application, or a complementary system to allow users to exchange messages during game matches or in other kind of applications. In all cases SmartFoxServer provides additional features to build a complete chat system, like moderation controls, anti-flood filtering capabilities and an advanced words filter which supports regular expressions and white-list/black-list modes.
The Simple Chat example just shows how to use the basic public messages, to keep the graphical interface as simple as possible. We leave to you to extend it to include private messaging, moderation controls or activate the anti-flood and words filtering.
As with the Connector example, when the application is launched, the user is prompted to enter SmartFoxServer 2X connection details (the pre-filled connection parameters used by this example are the same as for the previous examples; check the tutorial for additional informations on the default value for the IP address).
After the details are submitted, a connection to SmartFoxServer 2X is attempted and an event is then fired to notify if the connection has been established successfully.
Once connected to SmartFoxServer 2X the user is asked to enter a handle for the chat session. Using this handle, the user is logged into the BasicExamples Zone available in SFS2X by default. As a logged in user, we can then toggle between two views, one that displays status updates and public chat messages, and the other that simply lists all users logged into the Room joined by default.
>> 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:
- Make sure your SmartFoxServer 2X installation contains the BasicExamples Zone definition;
- Start SmartFoxServer 2X;
- In Eclipse, import the Android project contained in the /source folder from the download above;
- Launch the app and change the connection details if your SmartFoxServer 2X is not installed on your machine's localhost.
» Code highlights
In this example we follow the same scheme as in the Connector, so the connection steps basically the same the only difference is that we ask the user for a Nick instead of using an empty string
The application contains 3 layouts (located in the layout folder of the project):
- The connector layout: Where we choose the IP and port and select “Connect”
- The login layout: Where the nick name is entered
- And the chat layout: This view contains a TabHost with two tabs, the first one for the chat itself and the other one for the list that provides the users currently connected to the room.
To keep the code as simple as possible, layouts are wrapped in a FrameLayout. This container uses the showLayout method to show the appropriate layout (In a real application, activities or fragments are more suitable to implement this idea)
The class ChatMessage.java represents a message for the chat holding the following attributes and its getters/setters
public class ChatMessage { private String username; private String message; private Date date; private boolean incomingMessage; /* Getters and setters */ ... }
An ArrayAdapter is used to manage the list of users as they join and leave the default room and a custom ArrayAdapter (MessagesAdapter.java) to display the messages. For each message the MessagesAdapter inflates the layout row_message.xml and sets the texts, background and gravity depending on the kind of message (incoming, outgoing or system message).
The following code is invoked when the user hits the Send button at the bottom of the Chat tab. It takes the text entered in the input field and, as long as it is not empty, creates a new PublicMessageRequest which is sent to the server.
String message = inputChatMessage.getText().toString(); if (message.length() > 0) { // As long as message is non-blank create a new // PublicMessage and send to the server sfsClient.send(new PublicMessageRequest(message)); inputChatMessage.setText(""); }
Incoming server events are, like in the previous example, handled in an overridden dispatch method. For this example, we listen to a new event, PUBLIC_MESSAGE. When we receive an incoming public message we build a ChatMessage and add it to the MessagesAdapter. We also listen the USER_ENTER_ROOM and USER_EXIT_ROOM in order to keep the user’s tab up to date.
@Override public void dispatch(final BaseEvent event) throws SFSException { ... else if (event.getType().equals(SFSEvent.USER_ENTER_ROOM)) { final User user = (User) event.getArguments().get("user"); adapterUsers.add(user.getName()); updateUsersTabLabel(); adapterMessages.add(new ChatMessage("User '" + user.getName() + "' joined the room")); } // When a user leave the room the user list is updated else if (event.getType().equals(SFSEvent.USER_EXIT_ROOM)) { final User user = (User) event.getArguments().get("user"); adapterUsers.remove(user.getName()); updateUsersTabLabel(); adapterMessages.add(new ChatMessage("User '" + user.getName() + "' left the room")); } // When public message is received it's added to the chat // history else if (event.getType().equals(SFSEvent.PUBLIC_MESSAGE)) { ChatMessage message = new ChatMessage(); User sender = (User) event.getArguments().get("sender"); message.setUsername(sender.getName()); message.setMessage(event.getArguments().get("message").toString()); message.setDate(new Date()); // If my id and the sender id are different is a incoming // message message.setIncomingMessage(sender.getId() != sfsClient.getMySelf().getId()); adapterMessages.add(message); } }
As in the Connector example we free the resources in the Activity's onDestroy:
/** * 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(); } }
» More resources
You can learn more about the SmartFoxServer basics described in this tutorial by consulting the following resources:
- The login phase (server login basics)
- Join and create Rooms (joining a server Room)