Package | net.user1.reactor |
Class | public class Client |
Inheritance | Client ![]() |
Implements | IClient |
Since : | Reactor 1.0.0 |
The Client class represents a unique client that is connected to Union Server. Each client can send and receive messages and store shared data in client attributes.
To learn how Client objects represent client connections in Reactor's API, let's consider a simple chat application, chat.swf, running on two separate computers, "A" and "B". When chat.swf starts on computer A, it connects to Union Server using the following code:
var reactor:Reactor = new Reactor(); reactor.connect("tryunion.com", 80);
When the connection from computer A's chat.swf to Union Server is established, Union Server creates a server-side client object for the socket opened by computer A's chat.swf, and assigns that client a unique clientID (such as "37"). Likewise, when the connection from computer B's chat.swf to Union Server is established, Union Server creates a second client object and assigns it a unique clientID (such as "38"). At this stage, the two clients are connected to the server, but have no knowledge of each other.
To gain knowledge of each other, the two clients--let's call them clientA (for computer A's chat.swf) and clientB (for computer B's chat.swf)--join a room. Here's the "join-room" code that runs in each chat.swf
var room:Room = reactor.getRoomManager().createRoom("examples.chat"); room.join();
Upon joining the room "examples.chat", each client is automatically sent a list of the room's "occupants" (the clients in the room). Let's suppose computer A's chat.swf joins the room first, and is sent a list of room occupants for the room "examples.chat". Because clientA was the first client in the room, the list contains clientA only. (If there had already been other occupants in the room, they would also have been included in the list.) After clientA receives the room's occupant list, it triggers a RoomEvent.JOIN event. Once that event has fired, computer A's chat.swf can access the clients in the room using Room's getOccupants() method, as follows:
room.addEventListener(RoomEvent.JOIN, joinListener); protected function joinListener (e:RoomEvent):void { trace("Here are the room's occupants: " + Room(e.target).getOccupants()); }
Now suppose clientB joins the "examples.chat" room. Because clientA is already in the room, it receives notification that clientB joined the room, and the Room object in computer A's chat.swf triggers the RoomEvent.ADD_OCCUPANT event. That event gives clientA access to the Client object for clientB via the RoomEvent.getClient() method. The following code demonstrates:
room.addEventListener(RoomEvent.ADD_OCCUPANT, addOccupantListener); protected function addOccupantListener (e:RoomEvent):void { // In this example, e.getClient() is a reference to clientB's Client object trace("Someone joined the room: " + e.getClient()); }
Once clientA has a reference to clientB's Client object, clientA can access clientB's data by reading its attributes, and clientA can communicate with clientB by sending it messages. For example, in the following code, chat.swf sends a private message to clientB (and any other client that subsequently joins the room). Note that "PRIVATE_CHAT" is not a built-in message; it is a custom message name determined by the chat.swf application.
protected function addOccupantListener (e:RoomEvent):void { var newOccupant:Client = e.getClient(); // Send clientB a private message newOccupant.sendMessage("PRIVATE_CHAT", "Welcome to the chat room!"); }
In addition to joining rooms, clients can gain knowledge of each other via the ClientManager's watchForClients() and observeClient() methods. The watchForClients() method gives the current client knowledge of every client on the server. The observeClient() method gives the current client knowledge of one specific client. At any time, the Client object for any known client can be retrieved via ClientManager's getClient() method.
In addition to accessing other clients (referred to as "foreign clients"), each client can access the Client object representing its own connection via Reactor's self() method. The Client object representing a client's own connection is known as the current client. The following code displays the current client's clientID:
// Display current client's clientID. Note that the current client is // available only when Reator is in a ready state. See ReactorEvent.READY. trace(reactor.self().getClientID());
Clients store data in client attributes, which act as shareable multiuser variables. To retrieve a client's attribute values, use the Client class's getAttribute() method, as in:
var theClient:Client = reactor.getClientManager().getClient(someClientID); theClient.getAttribute(someAttributeName, someRoomID);
In the preceding code, someRoomID
is the attribute's scope and
someAttributeName
is the attribute's name.
To set a client's attributes use setAttribute(). Note, however, that
by default, a client can set its own attributes only, and cannot
set the attributes of other connected clients.
The following code retrieves the attribute "pieceColour", scoped to the room "chessGame", for the client with clientID 5:
var client:Client = getClientManager.getClient("5"); var pieceColour:String = client.getAttribute("pieceColour", "chessGame");
Likewise, the following code retrieves the global attribute "age" for client 5. Notice that the attribute scope is omitted, indicating that the attribute is global:
var client:Client = getClientManager.getClient("5"); var name:String = client.getAttribute("age");
It is not necessary to poll for changes in client attributes. When a client attribute is shared, changes to its value automatically trigger the RoomEvent.UPDATE_CLIENT_ATTRIBUTE event and the AttributeEvent.UPDATE event.
In order to reduce traffic between the server and clients, by default, not all clients on the server are accessible as Client instances. The current client has access to other clients in it's "sphere of knowledge" only, which includes synchronized rooms, "observed" clients (see ClientManager's observeClient() method), and "watched" clients (see ClientManager's watchForClients() method).
For example, suppose there are three rooms on the server. Further suppose that each room contains three clients. Here are the room names and list of client ids for the clients in each room:
chat1: 1, 2, 3 chat2: 1, 4, 5 chat3: 6, 7, 8
Because client 1 is in both the "chat1" room and the "chat2" room, its list of Client objects includes the clients with ids 1, 2, 3, 4, and 5. But client 1's list of Client objects does not include the clients with ids 6, 7, and 8 because client 1 is not in the "chat3" room. For more information on room synchronization see the Room class.
Applications can apply custom behaviour to connected clients by assigning a custom client class via the following methods: Client's setClientClass(), RoomManager's setDefaultClientClass(), and ClientManger's setDefaultClientClass().
Clients can save persistent data for later retrieval by creating and logging into a user account. User accounts are built-in to Union, and come ready to use with every Union Server installation. To login to an account, use the AccountManager's login() method. To access a logged-in client's user account, use the Client class's getAccount() method. For complete information on user accounts, see the UserAccount class.
In cases where an application wishes to retrieve a one-time snapshot of information about an arbitrary client on the server, and does not need that information to be kept up-to-date automatically, the application can use the ClientSnapshot class.
See also
Method | Defined By | ||
---|---|---|---|
Client(clientID:String, clientManager:ClientManager, messageManager:MessageManager, roomManager:RoomManager, connectionManager:ConnectionManager, server:Server, log:Logger)
Initializes Client instances. | Client | ||
ban(duration:int, reason:String = null):void
Disconnects this client from the server, and prevents any future connections
from this client's address (typically an IP address). | Client | ||
deleteAttribute(attrName:String, attrScope:String = null):void
Deletes the specified client attribute from the server. | Client | ||
dispose():void
Releases this client's resources. | Client | ||
Returns a reference to this client's UserAccount object, which is available
if this client has logged into a user account only. | Client | ||
getAttribute(attrName:String, attrScope:String = null):String
Returns the value of the specified client attribute. | Client | ||
getAttributes():Object
Returns an object whose variables represent the names and values of the
shared attributes for this client. | Client | ||
getAttributesByScope(scope:String = null):Object
Returns an object containing the names and values of all attributes
defined on this Client instance for a given scope, or for all scopes. | Client | ||
getClientID():String
Returns this client's unique ID, as set automatically by
the server. | Client | ||
Returns a reference to the ClientManager instance for this Client object. | Client | ||
getConnectionState():int
Indicates the state of the client's current server connection. | Client | ||
getConnectTime():Number
Returns the time that this client connected, as set by the server. | Client | ||
getIP():String
Returns this client's IP address, if available. | Client | ||
getObservedRoomIDs():Array
Returns the IDs of the rooms this client is known to be observing. | Client | ||
getOccupiedRoomIDs():Array
Returns the IDs of the rooms this client is known to be in. | Client | ||
getPing():int
Returns the client's ping time, in milliseconds. | Client | ||
getTimeOnline():Number
Returns the amount of time, in milliseconds, the specified Client has
been connected to the server. | Client | ||
getUpdateLevels(roomID:String):UpdateLevels
Returns this client's update levels for the specified room. | Client | ||
isAdmin():Boolean
Returns a Boolean indicating whether the client has administrator
privileges. | Client | ||
isInRoom(roomID:String):Boolean
Returns a Boolean value indicating whether this client is known to be in the
specified room. | Client | ||
isObservingRoom(roomID:String):Boolean
Returns a Boolean value indicating whether this client is known to be
observing the specified room. | Client | ||
isSelf():Boolean
Returns true if this client is the current client. | Client | ||
kick():void
Disconnects this client from the server. | Client | ||
observe():void
Asks the server to keep this client's state permanently synchronized. | Client | ||
sendMessage(messageName:String, ... arguments):void
Sends a message, with arguments, to another client. | Client | ||
setAttribute(attrName:String, attrValue:String, attrScope:String = null, isShared:Boolean = true, evaluate:Boolean = false):void
Sets a client attribute for this client. | Client | ||
setClientClass(scope:String, clientClass:Class, ... fallbackClasses):void
Specifies the class for the current client while it is in the room
with the specified scope. | Client | ||
setConnectionState(newState:int):void | Client | ||
stopObserving():void
Asks the server to stop observing this client. | Client | ||
toString():String [override]
Provides a string representation of this object. | Client |
Event | Summary | Defined By | ||
---|---|---|---|---|
Dispatched when an attribute is deleted. | Client | |||
Dispatched when the result of an attempt to delete an attribute is received. | Client | |||
Dispatched when the client that triggered this event joins a room. | Client | |||
Dispatched when the client that triggered this event leaves a room. | Client | |||
Dispatched when any client that is known to the current client logs in. | Client | |||
Dispatched when any user account that is known to the current client logs off. | Client | |||
Dispatched when the current client observes a client. | Client | |||
Dispatched when the result of an earlier Client.observe() or ClientManager.observeClient() request is received. | Client | |||
Dispatched when the client that triggered this event observes a room. | Client | |||
Dispatched when the result of an attempt to set an attribute is received. | Client | |||
Dispatched when the current client stops observing a client. | Client | |||
Dispatched when the result of an earlier Client.stopObserving() or ClientManager.stopObservingClient() request is received. | Client | |||
Dispatched when the client that triggered this event stops observing a room. | Client | |||
Dispatched when the client that triggered this event has been synchronized to match the state of the server due to an earlier observe() request. | Client | |||
Dispatched when an attribute changes or is set for the first time. | Client |
Client | () | Constructor |
public function Client(clientID:String, clientManager:ClientManager, messageManager:MessageManager, roomManager:RoomManager, connectionManager:ConnectionManager, server:Server, log:Logger)
Initializes Client instances. Note that Client instances are created automatically by ClientManager. Do not attempt to create Client instances manually.
ParametersclientID:String | |
clientManager:ClientManager | |
messageManager:MessageManager | |
roomManager:RoomManager | |
connectionManager:ConnectionManager | |
server:Server | |
log:Logger |
ban | () | method |
public function ban(duration:int, reason:String = null):void
Since : | Reactor 1.0.0 |
Disconnects this client from the server, and prevents any future connections from this client's address (typically an IP address). By default, ban() requires administrator privileges. To allow other types of clients (such as moderators) to ban addresses, define a remote-client security rule as described in Union Server's security documentation.
The result of the ban attempt is returned via a ClientManagerEvent.BAN_RESULT event, which is dispatched via the ClientManager (not this client).
Parameters
duration:int — The duration of the ban, in seconds.
| |
reason:String (default = null ) — An arbitrary, optional string indicating the reason for
the ban. The reason string is saved in the server-side
ban list.
|
See also
deleteAttribute | () | method |
public function deleteAttribute(attrName:String, attrScope:String = null):void
Since : | Reactor 1.0.0 |
Deletes the specified client attribute from the server. Other clients are notified of the change via the RoomEvent.DELETE_CLIENT_ATTRIBUTE and AttributeEvent.DELETE events.
Parameters
attrName:String — The name of the attribute to delete. Must not contain the
pipe character ("|").
| |
attrScope:String (default = null ) — A fully qualified roomID indicating the attribute's
scope. Use null to remove a global client attribute
(i.e., an attribute scoped to all rooms).
To retrieve a fully qualified roomID for a Room object,
use Room.getRoomID(). Defaults to null
(global attribute).
|
See also
dispose | () | method |
public function dispose():void
Releases this client's resources.
getAccount | () | method |
public function getAccount():UserAccount
Since : | Reactor 1.0.0 |
Returns a reference to this client's UserAccount object, which is available if this client has logged into a user account only.
ReturnsUserAccount |
See also
getAttribute | () | method |
public function getAttribute(attrName:String, attrScope:String = null):String
Since : | Reactor 1.0.0 |
Returns the value of the specified client attribute. Client attributes are assinged via the Client class's setAttribute() method, or directly by the server. See setAttribute() for full details on client attributes.
Parameters
attrName:String — The name of the attribute to retrieve.
| |
attrScope:String (default = null ) — The fully qualified roomID of the room to which
the attribute is scoped. For example,
"examples.chat". If null, the attribute is
retrieved from the global scope.
|
String — The string value of the attribute attrName .
|
See also
getAttributes | () | method |
public function getAttributes():Object
Since : | Reactor 1.0.0 |
Returns an object whose variables represent the names and values of the shared attributes for this client. Each variable name is a fully qualified attribute name. For example, given a client with a room-scoped attribute, "examples.chatroom1.username", set to "dan", and a global attribute, "gender", set to "male", the getAttributes() method would return an object with the following structure:
var o:Object(); o["examples.chatroom1.username"] = "dan"; o["gender"] = "male";
var o:Object(); o["examples.chatroom1"] = new Object(); o["examples.chatroom1"].username = "dan"; o[Tokens.GLOBAL_ATTR] = new Object(); o[Tokens.GLOBAL_ATTR]["gender"] = "male";
Object |
See also
var clientAttrs:Object = client.getAttributes(); for (var attrName in clientAttrs) { trace("Attribute: " + attrName + " has the value: " + clientAttrs[attrVal]); }
getAttributesByScope | () | method |
public function getAttributesByScope(scope:String = null):Object
Since : | Reactor 1.0.0 |
Returns an object containing the names and values of all attributes defined on this Client instance for a given scope, or for all scopes.
When scope is specified, the returned object has the following structure:
{name1:value1, name2:value2,...namen:valuen}When scope is not specified, the returned object has the following structure:
{scope1: {name1:value1, name2:value2,...namen:valuen}, scope2: {name1:value1, name2:value2,...namen:valuen}, scopen: {name1:value1, name2:value2,...namen:valuen}}For example, suppose a Client has two attributes, as follows:
var o:Object = new Object(); o[Tokens.GLOBAL_ATTR]["username"] = "derek"; o["games.pong"]["score"] = 8;
var o:Object = new Object(); o["username"] = "derek"; o["games.pong.score"] = 8;
Parameters
scope:String (default = null )
|
Object — A generic object containing the Client's attributes for a given
scope, or for all scopes.
|
See also
// The id for the client. For this example, use 3. var clientID = 3; // Retrieve an object representing attributes for all scopes. var attributesObj = reactor.getClientManager().getClient( clientID).getAttributesByScope(); // Enumerate all attributes in the global scope. for (var attrname:String in attributesObj[Tokens.GLOBAL_ATTR]) { trace("Global attribute name: " + attrname + " has the value: " + attributesObj[Tokens.GLOBAL_ATTR][attrname]); }
for (var scope:String in attributesObj) { for (var attrname in attributesObj[scope]) { trace("Attribute in scope: " + scope + " with the name: " + attrname + " has the value: " + attributesObj[scope][attrname]); } }
getClientID | () | method |
public function getClientID():String
Since : | Reactor 1.0.0 |
Returns this client's unique ID, as set automatically by the server. The client's id persists for the length of the client connection, and cannot be changed during that connection. A client's ID expires when the client disconnects.
Note that only two things are guaranteed about the client ID: 1) it is a string, and 2) it is unique on the server. The specific format of the client id is arbitrary, and is not guaranteed, nor should it be relied upon. For example, if the ID happens to be numeric (say, "35"), mathematical calculations should not be performed based on that number. The ID format is itself, subject to change without notice. It is hazardous to write client-side code that relies on the internal client ID itself rather than simply the fact that the ID is guaranteed to be unique. For a truly sequential ordering of clients, use the Client class's getConnectTime(), which returns the time on the server when a given client connected.
The client ID of the current client (i.e., reactor.self()) is available only after the ReactorEvent.READY event occurs.
Note that in addition to having a client ID, a client might also be logged into a user account that has a userID. Whereas a client ID is a temporary, automatically generated identifier for a single connection, a user ID is the name of a permanent server-side user account, and is available only after a client logs in. See the UserAccount class and the Client class's getAccount() method.
ReturnsString — This client's client ID.
|
See also
getClientManager | () | method |
public function getClientManager():ClientManager
Since : | Reactor 1.0.0 |
Returns a reference to the ClientManager instance for this Client object.
ReturnsClientManager |
See also
getConnectionState | () | method |
public function getConnectionState():int
Since : | Reactor 1.0.0 |
Indicates the state of the client's current server connection. The value is one of the constants of the ConnectionState class.
Returnsint |
See also
getConnectTime | () | method |
public function getConnectTime():Number
Since : | Reactor 1.0.0 |
Returns the time that this client connected, as set by the server. The time is represented in milliseconds-from-1970 format, and is given in UTC, set according to the server's clock. To convert the return of getConnectTime() to an ActionScript Date object, pass the value to the Date constructor, as in:
// Create a Date object representing the time theClient connected. var d:Date = new Date(theClient.getConnectTime());
theClient.getAttribute("_CT");
Number — The time, in milliseconds-from-1970 format, that this client
connected to the server, according to the server's clock.
|
See also
getIP | () | method |
public function getIP():String
Since : | Reactor 1.0.0 |
Returns this client's IP address, if available. Note that the IP address
is stored as a global client attribute named "_IP", so this method is
synonymous with theClient.getAttribute("_IP");
.
By default, a client knows its own IP address only, and does not
have access to the IP addresses of other clients on the server.
String — The string IP address for this Client.
|
getObservedRoomIDs | () | method |
public function getObservedRoomIDs():Array
Since : | Reactor 1.0.0 |
Returns the IDs of the rooms this client is known to be observing. The returned room list is based on the current client's knowledge of the rooms on the server, which may not fully reflect the actual server state. This method returns the IDs of rooms the client has observed, and does not include the IDs of rooms the client has joined.
The list of room IDs is a one-time snapshot, and is not kept up to date when the current client observes or stops observing rooms.
ReturnsArray — An array of room IDs.
|
See also
getOccupiedRoomIDs | () | method |
public function getOccupiedRoomIDs():Array
Since : | Reactor 1.0.0 |
Returns the IDs of the rooms this client is known to be in. The returned room list is based on the current client's knowledge of the rooms on the server, which may not fully reflect the actual server state. This method returns the IDs of rooms the client has joined, and does not include the IDs of rooms the client is merely observing.
The returned list of room IDs is a one-time copy of this Client's occupied room list, and is not kept up to date when the current client leaves or joins rooms.
ReturnsArray — An array of room IDs.
|
See also
getPing | () | method |
public function getPing():int
Since : | Reactor 1.0.0 |
Returns the client's ping time, in milliseconds. The "ping time"
is the amount of time it takes for a message to be sent from the client
to the server and back to the client (i.e., a complete
round-trip message). If the client's ping is not known, getPing() returns
-1
.
By default, each client pings the server every ten seconds, and getPing() returns the most recent ping time (not an average). Also by default, clients do not share their pings with other clients. Ping- time-sharing must be explicitly enabled via the ConnectionMonitor class. The getPing() method returns -1 for all clients that either have not shared their ping time or have disabled automatic ping-time calculation. For more information on ping configuration, see the ConnectionMonitor class.
Returnsint — The most recent ping time for the specified client, in
milliseconds, or -1 if the ping time is unknown.
|
See also
public function showPings (room:Room):void { var clients:Array = room.getOccupants(); for each (var client:int in clients) { trace("PING for client" + client.getClientID() + " is: " + client.getPing()); } }
getTimeOnline | () | method |
public function getTimeOnline():Number
Since : | Reactor 1.0.0 |
Returns the amount of time, in milliseconds, the specified Client has been connected to the server. The millisecond value is deduced by subtracting the client's connection time (retrieved via Client's getConnectTime() method) from the approximated current time on the server (retrieved via Server's getServerTime() method).
ReturnsNumber — The number of milliseconds the specified Client has been
connected to the server.
|
See also
getUpdateLevels | () | method |
public function getUpdateLevels(roomID:String):UpdateLevels
Since : | Reactor 1.0.0 |
Returns this client's update levels for the specified room. If the update levels are unknown, returns null.
Parameters
roomID:String |
UpdateLevels |
isAdmin | () | method |
public function isAdmin():Boolean
Since : | Reactor 1.0.0 |
Returns a Boolean indicating whether the client has administrator privileges. The administrator security role is available to clients that connect and authenticate over Union Server's administration port only.
ReturnsBoolean — true if the client has administrator privileges, false otherwise.
|
isInRoom | () | method |
public function isInRoom(roomID:String):Boolean
Since : | Reactor 1.0.0 |
Returns a Boolean value indicating whether this client is known to be in the specified room. Note that this method reflects the current client's awareness of the rooms on the server, not the actual state of the server. If the specified room is not synchronized and the client is not synchronized, then isInRoom() will always return false, even if the client is actually in the specified room. To guarantee that the result of isInRoom() is accurate for the specified roomID, join or observe the room and set sufficiently verbose room-update levels, or synchronize the client via either Client's observe() method or ClientManager's observeClient() method.
Parameters
roomID:String — The roomID of the room to check.
|
Boolean — Returns true if this Client object is known to be in the specified room.
|
See also
isObservingRoom | () | method |
public function isObservingRoom(roomID:String):Boolean
Since : | Reactor 1.0.0 |
Returns a Boolean value indicating whether this client is known to be observing the specified room. Note that this method reflects the current client's awareness of the rooms on the server, not the actual state of the server. If the specified room is not synchronized and the client is not synchronized, then isObservingRoom() will always return false, even if the client is actually observing the specified room. To guarantee that the result of isObservingRoom() is accurate for the specified roomID, join or observe the room and set sufficiently verbose room-update levels, or synchronize the client via either Client's observe() method or ClientManager's observeClient() method.
Parameters
roomID:String — The roomID of the room to check.
|
Boolean — Returns true if this Client object is known to be observing the specified room.
|
See also
isSelf | () | method |
public function isSelf():Boolean
Since : | Reactor 1.0.0 |
Returns true if this client is the current client. See Reactor's self() method.
ReturnsBoolean |
See also
kick | () | method |
public function kick():void
Since : | Reactor 1.0.0 |
Disconnects this client from the server. By default, requires moderator privileges.
The result of the kick attempt is returned via a ClientManagerEvent.KICK_RESULT event, which is dispatched via the ClientManager (not this client).
observe | () | method |
public function observe():void
Since : | Reactor 1.0.0 |
Asks the server to keep this client's state permanently synchronized. As a result, the current client is notified any time any of following:
Notifications from the server trigger the following events:
The result of an observe() call is returned via a ClientEvent.OBSERVE_RESULT event. If the call succeeds, the ClientEvent.OBSERVE event is triggered. After the client has been synchronized for the first time, the ClientEvent.SYNCRHONIZE event is triggered.
See also
sendMessage | () | method |
public function sendMessage(messageName:String, ... arguments):void
Since : | Reactor 1.0.0 |
Sends a message, with arguments, to another client. To receive the message, the recipient client defines a method (or multiple methods) to be executed when the message arrives. Each method wishing to be executed registers for the message separately using MessageManager's addMessageListener() method.
To send a message to an arbitrary list of individual clients instead of to a single client, use ClientManager.sendMessage().
Parameters
messageName:String — The name of the message to send to the specified
client.
| |
... arguments — An optional comma-separated list of
string arguments for the message.
|
See also
messageManager.addMessageListener("PRIVATE_CHAT", displayPrivateMessage);
theClient.sendMessage("PRIVATE_CHAT", message);
protected function displayPrivateChat (client:IClient, msg:String):void { privateChatField.text = "Private message from: " + client.getClientID() + ": " + msg); }
setAttribute | () | method |
public function setAttribute(attrName:String, attrValue:String, attrScope:String = null, isShared:Boolean = true, evaluate:Boolean = false):void
Since : | Reactor 1.0.0 |
Sets a client attribute for this client. The attribute and its value are stored on, and managed by, the server. A client attribute contains information about the client, much like a variable. However, unlike a basic variable, a client attribute and its value can be shared amongst other connected clients. Logged-in clients can also use user account attributes to save information to a database or other data source for later retrieval (see the UserAccount class's setAttribute() method for details).
Client attributes are used to track the characteristics of a client, such as a name, an age, a hair colour, or a score. For example, a client might store the value "39" in an attribute named "age" as follows:
theClient.setAttribute("age", "39");
Other connected clients could then access the age "39" on that client by retrieving its "age" attribute via Client.getAttribute(), as follows:
var client:Client = reactor.getClientManager().getClient(someClientID); var age:String = client.getAttribute("age");
In addition, if the client were to change its age from "39" to "40", other interested clients would be notified of the change. By responding to the change notification, other clients could, say, keep a user list for a chat room updated with the current user ages. The following code shows how to use a RoomEvent.UPDATE_CLIENT_ATTRIBUTE listener to respond the changing of a client attribute named "age":
protected function updateClientAttributeListener (e:RoomEvent):void { // If the attribute that changed was "age", then display // the client's new age. if (e.getChangedAttr().name == "age") { // Display an "age changed" message. trace(e.getClient() + " age changed to: " + e.getChangedAttr().value); } }
To be notified of changes to a specific client's attributes, applications can register with that client for the AttributeEvent.UPDATE event.
Every client attribute must be scoped to either a specific room or to all
rooms. A client attribute that is scoped to all rooms is known as a
"global client attribute". An attribute's scope determines which
clients are updated when the attribute changes.
For example, suppose a client is in the room
games.pong
and also in the room chat.lobby
. The
client sets an attribute named "score" with a scope of "games.pong" to the
value "10".
theClient.setAttribute("score", "10", "games.pong");
In response, other clients in the games.pong
room are notified
that the client's "score" attribute changed to "10". But clients in the
chat.lobby
room are not notified.
Next, suppose the client sets an attribute named "hairColour" to "brown" with
a scope of null
(null
indicates that the
attribute is globally scoped).
theClient.setAttribute("hairColour", "brown", null);
In response, other clients in both
games.pong
and chat.lobby
are notified that the
client's "hairColour" attribute was set to "brown". The scope of an
attribute allows a client to keep information pertinent to one room separate
from other rooms.
To delete a client attribute permanently, use Client's deleteAttribute() method. For example, the following code deletes the global client attribute "hairColour":
theClient.deleteAttribute("hairColour");
When a client attribute is deleted, rooms the client is in trigger the RoomEvent.DELETE_CLIENT_ATTRIBUTE event, and the Client object for the client triggers the AttributeEvent.DELETE event.
Client attributes are not deleted by the server until the client disconnects. Applications are expected to delete unwanted attributes explicitly via deleteAttribute(). Applications that create numerous client attributes for long-lasting connections should take care to prevent server-side memory accumulation by deleting each attribute after it is no longer needed.
Note that by default the pipe character ("|") is used internally to separate attributes during transimission to and from the server. Hence, attribute names and values must not contain the character "|". For more information, see Tokens.RS.
Parameters
attrName:String — The attribute name. Must not contain the pipe character ("|").
| |
attrValue:String — The attribute value. Must not contain the pipe character ("|").
| |
attrScope:String (default = null ) — A fully qualified roomID indicating the attribute's
scope. The client need not be in the room to use it as the attribute's
scope. However, when a client sets an attribute scoped to a room
it is not currently in, other clients in that room are not notified of
the attribute update.
To create a global attribute (i.e., an
attribute scoped to all rooms), set attrScope to null
(the default).
To retrieve a fully qualified room identifier for a Room object,
(for use as an attribute scope) use Room's getRoomID() method.
| |
isShared:Boolean (default = true ) — Flag indicating that interested clients should be notified when
the attribute changes (true ) or that no clients
should be notified when the attribute changes
(false ). Attribute updates are handled via
RoomEvent.UPDATE_CLIENT_ATTRIBUTE and AttributeEvent.UPDATE
listeners. Defaults to true (shared).
| |
evaluate:Boolean (default = false ) — If true, the server will evaluate the attrValue as a mathematical
expression before assigning the attribute its new value.
Within the expression, the token "%v" means "substitute
the attribute's current value". For example, the following
code adds one to an existing attribute "score":
theClient.setAttribute("score", "%v+1", null, true, true); .
When evaluate is true, attrValue can contain the following
characters only: the numbers 0-9, ., /, +, -, %, v.
|
See also
setClientClass | () | method |
public function setClientClass(scope:String, clientClass:Class, ... fallbackClasses):void
Since : | Reactor 1.0.0 |
Specifies the class for the current client while it is in the room with the specified scope. To set a global custom client class, set scope to null. The specified class (or one of the specified fallbackClasses) must be available to every other client that has knowledge of the current client.
Normally, the customClass extends CustomClient, which provides a basic template for custom client classes. If customClass does not extend CustomClient, it must manually compose a raw Client object, which can be retrieved via the ClientManager class's getInternalClient() method.
Parameters
scope:String — The room or rooms in which to use the specified class
for this client. Can be a single room ID or null for all rooms.
| |
clientClass:Class — The class to use for this client. The class is normally
a descendant of CustomClient, but can be any class that
implements the IClient interface.
| |
... fallbackClasses — A list of classes to use when the specified
clientClass cannot be found. The fallback classes are
useful when a client can appear in more than one application,
and each application represents the client with a different
class. For example, a client in a chess game might be depicted
by a custom client class, ChessClient. An administration tool
showing clients in a variety of games might choose to depict clients
with a different more general class, GameClient (in this example,
the GameClient class is the ChessClient class's superclass).
To accommodate needs of both the
chess application and the administration tool, the client would
set the clientClass argument to ChessClient, and fallbackClasses
to GameClient. The chess application would have access to
the ChessClient class, and would therefore use that class to
represent the client. The administration tool would not have
access to the ChessClass, so it would use the GameClient class
instead. Note, however, that if ChessClient were compiled into the
administration tool's application domain, then ChessClient
would be used instead of GameClient. That is, fallbackClasses
are, as the name suggests, used only as a fallback when
clientClass cannot be found.
|
See also
// Assign ChatClient as the default custom class for the current client // in all rooms. The default set here can be overridden for a specific // room via any Room object's setDefaultClientClass() method and via the // current client's setClientClass() method. reactor.self().setClientClass(null, ChatClient); // Assign ChessClient as the custom class for the current client in the // room "examples.chess" only (overrides the preceding default setting). reactor.self().setClientClass("examples.chess", ChessClient); // Set the default class to ChessClient for all clients in chessRoom. As a // result, any client that doesn't specify a custom class will become an // instance of ChessClient when retrieved via chessRoom.getClient(). chessRoom.setDefaultClientClass(ChessClient); // Set the default class to ChatClient for all clients in the application. // As a result, all clients in the application will become ChatClient // instances, unless they explicitly set a custom class, or are retrieved // via getClient() through a room that has a default client class set. reactor.getClientManager().setDefaultClientClass(ChatClient);
setConnectionState | () | method |
public function setConnectionState(newState:int):void
Parameters
newState:int |
stopObserving | () | method |
public function stopObserving():void
Since : | Reactor 1.0.0 |
Asks the server to stop observing this client. As a result, the server will no longer send notifications when the client's state changes.
The result of a stopObserving() call is returned via a ClientEvent.STOP_OBSERVING_RESULT event. If the call succeeds, the ClientEvent.STOP_OBSERVING event is also triggered.
See also
toString | () | method |
override public function toString():String
Since : | Reactor 1.0.0 |
Provides a string representation of this object.
ReturnsString |
DELETE | Event |
AttributeEvent
net.user1.reactor.AttributeEvent.DELETE
Dispatched when an attribute is deleted.
See also
DELETE_RESULT | Event |
AttributeEvent
net.user1.reactor.AttributeEvent.DELETE_RESULT
Dispatched when the result of an attempt to delete an attribute is received. To determine the result of the attempt, use getStatus(), which has the following possible return values:
See also
JOIN_ROOM | Event |
ClientEvent
net.user1.reactor.ClientEvent.JOIN_ROOM
Dispatched when the client that triggered this event joins a room.
See also
LEAVE_ROOM | Event |
ClientEvent
net.user1.reactor.ClientEvent.LEAVE_ROOM
Dispatched when the client that triggered this event leaves a room. This event also occurs when a room containing the target client is removed, forcing the client to leave.
See also
LOGIN | Event |
AccountEvent
net.user1.reactor.AccountEvent.LOGIN
Dispatched when any client that is known to the current client logs in. For a list of the situations in which a client becomes known to the current client, see the ClientManager's clientIsKnown() method. Note however, that the current client can opt out of login notification for room occupants and room observers by disabling "occupant-login-logoff updates" and "observer-login-logoff updates" via the Room class's setUpdateLevels() method.
The AccountEvent.LOGIN event is dispatched via the Client object for the client that logged in, then the UserAccount object for the logged-in account, then the AccountManager.
See also
LOGOFF | Event |
AccountEvent
net.user1.reactor.AccountEvent.LOGOFF
Dispatched when any user account that is known to the current client logs off. For a list of the situations in which a client becomes known to the current client, see the ClientManager's clientIsKnown() method. Note however, that the current client can opt out of logoff notification for room occupants and room observers by disabling "occupant-login-logoff updates" and "observer-login-logoff updates" via the Room class's setUpdateLevels() method.
The AccountEvent.LOGOFF event is dispatched via the Client object for the client that logged off, then the UserAccount object for the logged-off account, then the AccountManager.
See also
OBSERVE | Event |
ClientEvent
net.user1.reactor.ClientEvent.OBSERVE
Dispatched when the current client observes a client. The client that is now being observed can be accessed via ClientEvent's getClient() method.
See also
OBSERVE_RESULT | Event |
ClientEvent
net.user1.reactor.ClientEvent.OBSERVE_RESULT
Dispatched when the result of an earlier Client.observe() or ClientManager.observeClient() request is received.
See also
OBSERVE_ROOM | Event |
ClientEvent
net.user1.reactor.ClientEvent.OBSERVE_ROOM
Dispatched when the client that triggered this event observes a room.
See also
SET_RESULT | Event |
AttributeEvent
net.user1.reactor.AttributeEvent.SET_RESULT
Dispatched when the result of an attempt to set an attribute is received. To determine the result of the attempt, use getStatus(), which has the following possible return values:
See also
STOP_OBSERVING | Event |
ClientEvent
net.user1.reactor.ClientEvent.STOP_OBSERVING
Dispatched when the current client stops observing a client. The client that is no longer being observed can be accessed via ClientEvent's getClient() method.
See also
STOP_OBSERVING_RESULT | Event |
ClientEvent
net.user1.reactor.ClientEvent.STOP_OBSERVING_RESULT
Dispatched when the result of an earlier Client.stopObserving() or ClientManager.stopObservingClient() request is received.
See also
STOP_OBSERVING_ROOM | Event |
ClientEvent
net.user1.reactor.ClientEvent.STOP_OBSERVING_ROOM
Dispatched when the client that triggered this event stops observing a room. This event also occurs when a room containing the client is removed, forcing the client to stop observing the room.
See also
SYNCHRONIZE | Event |
ClientEvent
net.user1.reactor.ClientEvent.SYNCHRONIZE
Dispatched when the client that triggered this event has been synchronized to match the state of the server due to an earlier observe() request.
See also
UPDATE | Event |
AttributeEvent
net.user1.reactor.AttributeEvent.UPDATE
Dispatched when an attribute changes or is set for the first time.
See also