Reactor Chat Tutorial, Part 1
Sending a Chat Message
Now that we've joined the room, we can send a message to all of its occupants using the Room class's sendMessage() method, like this:
chatRoom.sendMessage("CHAT_MESSAGE",
true,
null,
"Hello world!");
The arguments in the preceding method-call are:
- "CHAT_MESSAGE": The message name
- true: Echo the message to the sender
- null: Don't filter the message (send it to all occupants)
- "Hello world!": The message's first, and only, argument.
Of course, we don't want to send "Hello world!" every time. Let's add a text field for the user to write a message. Pressing the Enter key will send the message.
package {
import flash.display.Sprite;
// Import text and keyboard classes
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.ui.Keyboard;
import net.user1.reactor.Reactor;
import net.user1.reactor.ReactorEvent;
import net.user1.reactor.Room;
public class UnionChatPart1 {
protected var reactor:Reactor;
protected var chatRoom:Room;
// Define a variable for the text field
protected var outgoingMessages:TextField;
public function UnionChatPart1 () {
// Call a method to create the user interface
buildUI();
reactor = new Reactor();
reactor.addEventListener(ReactorEvent.READY, readyListener);
reactor.connect("tryunion.com", 80);
}
protected function readyListener (e:ReactorEvent):void {
chatRoom = reactor.getRoomManager().createRoom("chatRoom");
chatRoom.join();
}
// Define a method to create the user interface
protected function buildUI ():void {
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);
addChild(outgoingMessages);
}
// Define a listener to handles key presses
protected function keyUpListener (e:KeyboardEvent):void {
if (e.keyCode == Keyboard.ENTER) {
chatRoom.sendMessage("CHAT_MESSAGE",
true,
null,
outgoingMessages.text);
outgoingMessages.text = "";
}
}
}
}