Tutorials > Tutorial 5: Text Chat

 

Tutorial 5: Text Chat

In Tutorial 2: Shared Text, you created a remote shared object that enabled a user to view another user's typing in real time, letter by letter. In this next tutorial, you'll create a different kind of shared object that sends whole messages on command. You'll also add several elements to make the text chat application more versatile, including fields for logging in, typing in a chat room name, and viewing the list of current participants.

 
Viewing the application

In a Web browser, open two instances of tutorial_textchat.html. Type your name and a room name in the first instance; type another user name and the same room name in the second instance. Both users are listed as connected and can exchange text messages. When users log in to a room, they are added to the list of connected users; when users log off, they are removed from the list.

 
Re-creating the application

The tutorial_textchat.fla file provides the ActionScript for letting multiple users share text in real time.

In a chat room, you want to view current users dynamically. When users log in to a room, the list should be updated; when users log off, they should be removed from the list. It's best to do this processing work on the server, because keeping data centrally on the server means that any client can come and go, and the data will always be accurate and available.

In addition, in this tutorial, the server doesn't simply hand off the text from one client to another—it actually makes changes to the message by adding the name of the user who typed it. Because you expect the server to provide this functionality, you need to write some Server-Side Communication ActionScript to handle this work.

Finally, this tutorial also illustrates how to dynamically add an instance name to a NetConnection.connect command based on data entered by the user.

Before you start to re-create the application, see "Creating your working environment" in Developing Communication Applications.

 
To create the user interface:

1

In the Macromedia Flash MX authoring environment, select File > New to open a new file.

2

To add a text box to enter a user name, select the Text tool and draw a text box on the Stage. In the Property inspector (Window > Properties), select Input Text for the type of text box, give it the instance name User, and select the Show Border Around Text option.

3

To add a text box to enter the name of a chat room to join, draw another text box below the User text box. In the Property inspector (Window > Properties), select Input Text for the type of text box, give it the instance name Room, and select the Show Border Around Text option.

4

To add a text box to type messages, draw another text box below the Room text box. In the Property inspector, select Input Text for the type of text box, give it the instance name Message, and select the Show Border Around Text option.

5

To display the chat history, draw a fourth text box below the Message text box. In the Property inspector, select Dynamic Text for the type of text box, give it the instance name History, and select the Show Border Around Text option.

6

To add a place where users are listed, open the Components panel (Windows > Components), drag the List Box component onto the Stage, and give it the instance name People.

7

To add the button to connect to the server, drag a push button from the Components panel and place it on the Stage next to the User and Room text boxes. In the Property inspector, give it the instance name Connect_btn, the label Connect, and the click handler doConnect.

8

To add the button to send messages, drag a push button from the Components panel and place it on the Stage next to the Message text box. In the Property inspector, give it the instance name Send_btn, the label Send, and the click handler doSend.

9

Save the file as tutorial_textchat.fla.

10

To register the application with the server, create a directory with the same name as your application, tutorial_textchat, in your /applications directory in the Flash Communication Server directory.

 
To write the client-side ActionScript:

1

Select the keyframe in the Timeline and open the Actions panel (Window > Actions).

2

In the Actions panel, stop the progress of the movie.

stop();

3

Provide a value for the maximum scrolling of the History text box component.

// Set maximum scroll
History.maxscroll = 1000;

4

Prevent the user from sending until after the user has connected to the server.

// Don't allow the user to send until after connection
_root.Send_btn.setEnabled(false);

5

Create a new connection object.

// Open a connection to the server
client_nc = new NetConnection();

6

Provide an onStatus for the connection object function to handle any connection status messages. If the connection has been closed, the History text box and the People list box are cleared of all content.

// If connection is closed, clear the History and the list
client_nc.onStatus = function(info) {

	trace("Level: " + info.level + "   Code: " +  info.code);

	if (info.description == "NetConnection.Connect.Closed") {
		History.text = "";
		_root.People.removeAll();
	}
}

7

Create the event handler for the Connect button. If the user clicked the button when the label was Connect, then connect to the server and update the buttons.

function doConnect() {
	
	if (Connect_btn.getLabel() == "Connect") {
		
		// Connect to the chat application. 
		// The second parameter, _root.Room.text,
		// is the application instance.
		_root.client_nc.connect("rtmp:/tutorial_textchat/" + _root.Room.text,
												_root.User.text);

		// Update button label
		Connect_btn.setLabel("Disconnect");
	
		// Enable send button
		_root.Send_btn.setEnabled(true);

8

In the same doConnect function, create a remote shared object and connect to it.

		// Create a remote shared object to keep track
		// of the users. The value client_nc.uri is the URI of the
		// NetConnection the shared object will use to connect to the
		// server. I.e., the one just created.
		users_so = SharedObject.getRemote("users_so", _root.client_nc.uri,
																false);

		// Attach the shared object to client_nc
		users_so.connect(_root.client_nc);

9

In the same doConnect function, create the onSync method to handle the change in users.

		// When the list of users_so is updated, refresh the 
		// People list box.
		users_so.onSync = function(userList) {

			_root.People.removeAll();

			for ( var i in users_so.data) {
				if (users_so.data[i] != null) {
					_root.People.addItem(users_so.data[i]);
				}
			}

			// Sort alphabetically, because order returned
			// is not guaranteed to be consistent.
			_root.People.sortItemsBy("label", "ASC");
		}

10

In the same doConnect function, provide a callback function to be called by the server.

		// Update the shared object with the message.
		users_so.msgFromSrvr = function(msg) {
	
			_root.History.text += msg;
			_root.History.scroll = _root.History.maxscroll;
			historyScroll.setScrollTarget(history);
			historyScroll.setScrollPosition(_root.History.maxscroll);
		}
	} 

11

Lastly, in the same doConnect function, if the label on the Connect button is Disconnect, then close the connection and reset the buttons.

	else if (Connect_btn.getLabel() == "Disconnect") {

		// Close connection
		_root.client_nc.close();

		// Don't allow the user to send when not connected
		_root.Send_btn.setEnabled(false);

		// Rest button label
		Connect_btn.setLabel("Connect");

	}
} // doConnect function ends here

12

Create an event handler for when the user selects Send. In this function, if there's any text in the Message input text box, call the server function, msgFromClient, and pass it the Message.text text.

// Send the message text by calling the server message function 
function doSend() {

	// If there's message text, pass it to the server function msgFromClient
	if (length(_root.Message.text) > 0) {
		_root.client_nc.call("msgFromClient", null, _root.Message.text);
	}

	// Clear the message text
	_root.Message.text = "";

}

13

Create the setHistory function that the server calls to update the text in the History dynamic text box.

// Update the History on the server with the message
client_nc.setHistory = function(msg) {
	_root.History.text = msg;
}

 
To write the server-side ActionScript:

1

Create a new file using your server-side ActionScript editor or text editor, and write the event handler onAppStart for initializing the application variables.

application.onAppStart = function()
{
	trace("Begin sharing text");
	
	// Get the server shared object users_so
	application.users_so = SharedObject.get("users_so", false);
	
	// Initialize the history of the text share
	application.history = "";
	
	// Initialize the unique user ID
	application.nextId = 0;
}

2

Write the event handler onConnect for managing users and sending the history to all clients.

application.onConnect = function(newClient, name)
{
	// Make this new client's name the user's name
	newClient.name = name;
	
	// Create a unique ID for this user while incrementing the
	// application.nextID.
	newClient.id = "u" + application.nextId++;
	
	// Update the users_so shared object with the user's name
	application.users_so.setProperty(newClient.name, name);
	
	// Accept the client's connection
 	application.acceptConnection(newClient);
	
	// Call the client function setHistory, and pass 
	// the initial history
 	newClient.call("setHistory", null, application.history);

	// The client will call this function to get the server
	// to accept the message, add the user's name to it, and
	// send it back out to all connected clients.
	newClient.msgFromClient = function(msg) {	
		msg = this.name + ": " + msg + "\n";
		application.history += msg;
		application.users_so.send("msgFromSrvr", msg);
	}
}

3

Write the event handler onDisconnect to clean up.

application.onDisconnect = function(client)
{
	trace("disconnect: " + client.name);
	application.users_so.setProperty(client.name, null);
}

4

Save the file as main.asc in the tutorial_textchat directory you previously created under the /applications directory in the Flash Communication Server directory.

Note: Save this main.asc file in the registered client application directory in the location you've chosen to store your server-side application files.

 
To test your application:

1

In the Flash MX authoring environment, after you have saved your work, publish it by selecting File > Publish.

2

Open two instances of the SWF file.

3

In each instance, type a user name and room name, and click Connect. (Make sure to choose different user names but the same room name in both instances.) Each each user name you enter appears in the People list box. Type a message in the Message text box and click Send to see the message appear in both instances of the SWF.