Reactor Chat Tutorial, Part 1
Receiving a Chat Message
To receive a message, we register a message listener with the chat room. In this case, we're interested in messages named "CHAT_MESSAGE", so the code looks like this:
chatRoom.addMessageListener("CHAT_MESSAGE", chatMessageListener);
When a chat message arrives, we'll display it on screen in a text field. Here's the new code:
package { import flash.display.Sprite; import flash.events.KeyboardEvent; import flash.text.TextField; import flash.text.TextFieldType; import flash.ui.Keyboard; // Import the IClient class import net.user1.reactor.IClient; import net.user1.reactor.Reactor; import net.user1.reactor.ReactorEvent; import net.user1.reactor.Room; public class UnionChatPart1 extends Sprite { protected var reactor:Reactor; protected var chatRoom:Room; // Define a variable for the "incoming" text field protected var incomingMessages:TextField; protected var outgoingMessages:TextField; public function UnionChat () { buildUI(); reactor = new Reactor(); reactor.addEventListener(ReactorEvent.READY, readyListener); reactor.connect("tryunion.com", 80); } protected function readyListener (e:ReactorEvent):void { // Display the connection status on screen incomingMessages.appendText("Connected to Union\n"); chatRoom = reactor.getRoomManager().createRoom("chatRoom"); chatRoom.addMessageListener("CHAT_MESSAGE", chatMessageListener); chatRoom.join(); } protected function buildUI ():void { // Create a text field to show incoming chat messages incomingMessages = new TextField; incomingMessages.border = true; incomingMessages.background = true; incomingMessages.width = 400; incomingMessages.height = 200; outgoingMessages = new TextField; outgoingMessages.type = TextFieldType.INPUT; outgoingMessages.border = true; outgoingMessages.background = true; outgoingMessages.width = 400; outgoingMessages.height = 20; outgoingMessages.y = 210; outgoingMessages.addEventListener(KeyboardEvent.KEY_UP, keyUpListener); // Add the "incoming messages" text field to the screen addChild(incomingMessages); addChild(outgoingMessages); } protected function keyUpListener (e:KeyboardEvent):void { if (e.keyCode == Keyboard.ENTER) { chatRoom.sendMessage("CHAT_MESSAGE", true, null, outgoingMessages.text); outgoingMessages.text = ""; } } // Define the listener for "CHAT_MESSAGE" messages. // The "fromClient" is the client that sent the message. // messageText is the value of the 4th argument to the // sendMessage() call, above (i.e., outgoingMessages.text) protected function chatMessageListener (fromClient:IClient, messageText:String):void { incomingMessages.appendText("Guest" + fromClient.getClientID() + " says: " + messageText + "\n"); } } }