Reactor Chat Tutorial, Part 1
The Final Code
Here's the final code for the chat, ready to compile and run. It rings in at a svelte 70 lines.
package { import flash.display.Sprite; import flash.events.KeyboardEvent; import flash.text.TextField; import flash.text.TextFieldType; import flash.ui.Keyboard; 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; protected var incomingMessages:TextField; protected var outgoingMessages:TextField; public function UnionChatPart1 () { buildUI(); reactor = new Reactor(); reactor.addEventListener(ReactorEvent.READY, readyListener); reactor.connect("tryunion.com", 80); } protected function readyListener (e:ReactorEvent):void { incomingMessages.appendText("Connected to Union\n"); chatRoom = reactor.getRoomManager().createRoom("chatRoom"); chatRoom.addMessageListener("CHAT_MESSAGE", chatMessageListener); chatRoom.join(); } protected function buildUI ():void { 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); 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 = ""; } } protected function chatMessageListener (fromClient:IClient, messageText:String):void { incomingMessages.appendText("Guest" + fromClient.getClientID() + " says: " + messageText + "\n"); } } }
Well that was fun! Why not keep going? You can learn more about creating Union applications for Adobe Flash with these resources: