Packagenet.user1.reactor
Classpublic class MessageManager
InheritanceMessageManager Inheritance Object

Since : Reactor 1.0.0

The MessageManager class provides a set of services related to sending and receiving messages between the client and server. Each connection has only one MessageManager, which is created automatically by Reactor, and can be accessed via Reactor's getMessageManager() method.

The MessageManager is used to perform the following tasks:

See also

addMessageListener()
sendUPC()


Public Methods
 MethodDefined By
  
Initializes MessageManager instances.
MessageManager
  
addMessageListener(message:String, listener:Function, forRoomIDs:Array = null):Boolean
Registers a method or function (hereafter, the "message listener") to be executed when the specified type of message is received from the server.
MessageManager
  
dispose():void
MessageManager
  
Returns the number of messages that have been received by the MessageManager.
MessageManager
  
Returns the number of messages that have been sent by the MessageManager.
MessageManager
  
Returns a Boolean indicating whether automatic message-listener removal is enabled (true) or disabled (false).
MessageManager
  
Returns the number of messages that have been sent and received by the MessageManager.
MessageManager
  
hasMessageListener(message:String, listener:Function):Boolean
Returns a Boolean indicating whether the specified listener function is currently registered to receive message notifications for the specified message.
MessageManager
  
removeMessageListener(message:String, listener:Function):Boolean
Unregisters a message listener method that was earlier registered for message notifications via addMessageListener().
MessageManager
  
Enables or disables automatic message-listener removal.
MessageManager
  
sendUPC(m:String, ... rest):void
Creates and sends a UPC-formatted message to the server.
MessageManager
  
sendUPCObject(upc:UPC):void
Sends a UPC-formatted message to the server, based on the supplied UPC object.
MessageManager
Constructor Description
MessageManager()Constructor
public function MessageManager(reactor:Reactor)

Initializes MessageManager instances. Note that each connection's MessageManager instance is created automatically. Do not create MessageManager instances manually.

Parameters
reactor:Reactor — The Reactor instance that created this MessageManager.
Method Descriptions
addMessageListener()method
public function addMessageListener(message:String, listener:Function, forRoomIDs:Array = null):Boolean

Since : Reactor 1.0.0

Registers a method or function (hereafter, the "message listener") to be executed when the specified type of message is received from the server. The message can be a built-in UPC message, or a custom message sent to the client by a server-side module or by another client via the sendMessage() method of the Room, RoomManager, Client, ClientManager, or Server classes. Messages listeners are executed in the order they were added.

For example, the following code registers a method, displayPrivateMessage, to receive messages called "PRIVATE_CHAT" from other clients:

messageManager.addMessageListener("PRIVATE_CHAT", displayPrivateMessage);
The following code sends the "PRIVATE_CHAT" message to theClient via sendMessage():
theClient.sendMessage("PRIVATE_CHAT", message);
The following code shows the displayPrivateChat() method, which handles incoming "PRIVATE_CHAT" messages:
    
     protected function displayPrivateChat (client:IClient, 
                                            msg:String):void {
       privateChatField.text = "Private message from: " + client.getClientID() 
                             + ": " + msg);
     }
     

Typically, MessageManager's addMessageListener() method is not used to register listeners for messages sent via Room's sendMessage() method. Messages sent to a single room via Room's sendMessage() method are normally handled by listeners registered using the Room class's addMessageListener() method instead of MessageManager's addMessageListener(). The Room class's version of addMessageListener() provides a convenient wrapper for the functionality provided by MessageManager's addMessageListener().

MessageManager's addMessageListener() method can be used to register listeners that handle messages centrally for a group of rooms. For example, suppose a multi-room chat application displays a notification icon when a new message is received in any room. To catch all incoming messages for all rooms, the application registers a single, centralized method for all "CHAT" messages. Here's the registration code:

msgManager.addMessageListener(Messages.CHAT, centralChatListener);

The centralChatListener() then executes any time the Messages.CHAT message is sent to any room.

To display each chat message in its appropriate room, the application also registers for Messages.CHAT messages through each individual room. For example, the following code causes roomOneChatListener() to run any time a Messages.CHAT message is sent to roomOne:

roomOne.addMessageListener(Messages.CHAT, roomOneChatListener);

Each chat message sent to roomOne, hence, triggers both centralChatListener() and roomOneChatListener(), allowing each method to handle the message in its own way.

To register a listener to handle a given message for a limited subset of rooms, use the forRoomIDs parameter. For example, suppose the current client is in rooms "chat1", "chat2", and "chat3". A message called "WINK" is occasionally sent to one of those rooms by its occupants. To register a message listener for "WINK" messages sent to rooms "chat1" and "chat2", but not "chat3", use the following code (notice the value of the third argument, forRoomIDs):

     messageManager().addMessageListener("WINK", 
                                         winkListener,
                                         ["chat1", "chat2"]);
     

The preceding code could be used to implement a GUI option to "disable winks" from the occupants of room "chat3".

The code for the winkListener() method follows. Notice that its second argument (toRoom) receives a reference to the room to which the message was sent.

     private function winkListener (client:IClient,
                                    toRoom:Room):void {
      // Code here would display the wink on screen
     }
     

Message listeners registered via MessageManager's addMessageListener() method must define the correct number and type of parameters for the incoming message, as follows:

Advanced note: although the datatype of a message listener's first argument (the "from client") is normally IClient, it can be more specific. If the "from client" has registered a custom client class for the message's recipient room, then the listener's first argument can be typed to that custom client class.

For example, imagine hybrid chat-and-chess application in which the user can chat while waiting for an opponent to move. As an occupant of the chess room, the user's client is represented by the class ChessClient. The ChessClient class is registered with the following code:

     reactor.self().setClientClass("ChessClient", chessRoom);
     

While chatting, the user wants to receive an alert whenever his opponent moves, so the application registers a central listener for the message Messages.MOVE:

     msgManager.addMessageListener(Messages.MOVE,
                                   moveAlertListener);
     

In the preceding code, notice that the addMessageListener() call does not supply a forRoomIDs argument, so the moveAlertListener() is triggered anytime Messages.MOVE is sent to any room that the the current client is in or observing. When the opponent moves, the opponent's client sends the following message to the "games.chessRoom" room:

     chessRoom.sendMessage(Messages.MOVE, false, null, piece, coords);
     

The moveAlertListener() method is invoked when the message is received. Because the message was sent to the chessRoom, the sender is automatically represented by the ChessClient class, so the datatype of the first parameter can be set to ChessClient. The moveAlertListener() method can then use the methods of the ChessClient class to, say, display the opponent's ranking without ever leaving the chat interface:

     private function moveAlertListener (client:ChessClient, 
                                         piece:String,
                                         coords:String):void {
       alertField.text = client.getName() + " (Ranking: " 
                       + client.getRanking() + ") just moved!";
     }

For more information on custom client classes, see the Client class's setClientClass() method.

Note: failure to provide the mandatory IClient parameter for a message listener will result in an argument error such as the following:
     Error: A message listener for incoming message [CHAT_MESSAGE], received 
     from client [291], encountered an argument error:
     
     ArgumentError: Error #1063: Argument count mismatch on 
     UnionChatPart1/chatMessageListener(). Expected 1, got 2.
     
     Ensure that all [CHAT_MESSAGE] listeners supply a first parameter whose 
     datatype is IClient (or a compatible type). Listeners that registered for
     the message via MessageManager's addMessageListener() method with anything 
     other than a single roomID for the toRoomIDs parameter must define a second 
     paramter whose datatype is Room (or a compatible type). Finally, ensure 
     that the listeners declared message parameters match the following actual 
     message arguments:
         hello world
     
     Stack trace follows:
       at CoreMessageListener/u7()[/net/user1/reactor/CoreMessageListener.as:269]
       at Function/http://adobe.com/AS3/2006/builtin::apply()
       at net.user1.reactor::MessageManager/notifyMessageListeners()[/net/user1/reactor/MessageManager.as:666]
       at net.user1.reactor::MessageManager/upcReceivedListener()[/net/user1/reactor/MessageManager.as:266]
       at flash.events::EventDispatcher/dispatchEventFunction()
       at flash.events::EventDispatcher/dispatchEvent()
       at net.user1.reactor::XMLSocketConnection/dataListener()[/net/user1/reactor/XMLSocketConnection.as:225]
       at flash.events::EventDispatcher/dispatchEventFunction()
       at flash.events::EventDispatcher/dispatchEvent()
       at flash.net::XMLSocket/scanAndSendEvent()
     

To fix an argument error for a message listener, add the required IClient parameter, and if necessary, the required Room parameter. For example, the following listener code will generate an error because it lacks the mandatory IClient parameter:

     // INCORRECT:
     protected function chatMessageListener (messageText:String):void {
     }
     
The following code fixes the preceding error by adding an IClient parameter:
     // CORRECT (note the addition of the fromClient parameter):
     protected function chatMessageListener (fromClient:IClient,
                                             messageText:String):void {
     }
     

Parameters

message:String — The name of the message the listener is registering to receive.
 
listener:Function — The function or method that will be invoked when the specified message is received. The rules describing the required datatypes of the listener's parameters are listed under the addMessageListener() method documentation.
 
forRoomIDs:Array (default = null) — A list of room IDs. If the message was sent to any of the rooms in the list, the listener is executed. Otherwise, the listener is not executed. Applies to messages sent to rooms only, not to messages sent to specific individual clients or the entire server.

Returns
Boolean — If the registration succeeded, true; otherwise, false. If the specified listener is already registered, returns false.

See also

dispose()method 
public function dispose():void

getNumMessagesReceived()method 
public function getNumMessagesReceived():int

Since : Reactor 1.0.0

Returns the number of messages that have been received by the MessageManager. Used for statistics tracking and load testing.

Returns
int

See also

getNumMessagesSent()method 
public function getNumMessagesSent():int

Since : Reactor 1.0.0

Returns the number of messages that have been sent by the MessageManager. Used for statistics tracking and load testing.

Returns
int

See also

getRemoveMessageListenersOnDisconnect()method 
public function getRemoveMessageListenersOnDisconnect():Boolean

Since : Reactor 1.0.0

Returns a Boolean indicating whether automatic message-listener removal is enabled (true) or disabled (false).

Returns
Boolean — The Boolean value true or false.

See also

getTotalMessages()method 
public function getTotalMessages():int

Since : Reactor 1.0.0

Returns the number of messages that have been sent and received by the MessageManager. Used for statistics tracking and load testing.

Returns
int

See also

hasMessageListener()method 
public function hasMessageListener(message:String, listener:Function):Boolean

Since : Reactor 1.0.0

Returns a Boolean indicating whether the specified listener function is currently registered to receive message notifications for the specified message.

Parameters

message:String — The string ID of a Union message.
 
listener:Function — A function or method.

Returns
Boolean

See also

removeMessageListener()method 
public function removeMessageListener(message:String, listener:Function):Boolean

Since : Reactor 1.0.0

Unregisters a message listener method that was earlier registered for message notifications via addMessageListener(). Note that by default, all message listeners are automatically removed when the connection to the server is closed.

Parameters

message:String — The string ID of the message for which the listener is unregistering.
 
listener:Function — The function or method to unregister.

Returns
Boolean — A Boolean indicating whether the listener was successfully removed.

See also

removeMessageListenersOnDisconnect()method 
public function removeMessageListenersOnDisconnect(enabled:Boolean):void

Since : Reactor 1.0.0

Enables or disables automatic message-listener removal. By default, when the connection to the server is lost, MessageManager automatically removes all registered message listeners. This automatic removal prevents listeners from becoming stranded and having unintended side effects when the connection is restored. To disable automatic message listener removal, pass false to removeMessageListenersOnDisconnect(). When automatic message listener removal is diabled, be careful to remove all unwanted message listeners manually at disconnection time.

Parameters

enabled:Boolean — When true, automatic message listener removal is enabled. When false, automatic message listener removal is disabled.

See also

sendUPC()method 
public function sendUPC(m:String, ... rest):void

Since : Reactor 1.0.0

Creates and sends a UPC-formatted message to the server. This method is used internally to send UPC-formatted messages to the server. Any UPC-formatted response from the server will trigger a ConnectionEvent.RECEIVED_UPC event.

The sendUPC() parameter m specifies the value of the <m> element in the UPC message, while all remaining parameters specify the values of the <a> elements in the UPC message.

For complete details on UPC-formatted messages, see the UPC Specification.

Parameters

m:String — The message name.
 
... rest — Arguments for the message.

See also

sendUPCObject()method 
public function sendUPCObject(upc:UPC):void

Sends a UPC-formatted message to the server, based on the supplied UPC object.

Parameters

upc:UPC — The UPC message object.