flash.net

# NetGroup - AS3

Package | flash.net
Class | public class NetGroup
Inheritance | NetGroup EventDispatcher Object

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Instances of the NetGroup class represent membership in an RTMFP group. Use this class to do the following:

- Monitor Quality of Service. The `info` property contains a NetGroupInfo object whose properties provide QoS statistics for this group.
- Posting. Call `post()` to broadcast ActionScript messages to all members of a group.
- Direct routing. Call `sendToNearest()`, `sendToNeighbor()`, and `sendToAllNeighbors()` to send a short data message to a specific member of a peer-to-peer group. The source and the destination do not need to have a direct connection.
- Object replication. Call `addHaveObjects()`, `removeHaveObjects()`, `addWantObjects()`, `removeWantObjects()`, `writeRequestedObject()`, and `denyRequestedObject()` to break up large data into pieces and replicate it to all nodes in a peer-to-peer group.

In the client-side NetGroup class, the NetConnection dispatches the following events:

- NetGroup.Connect.Success
- NetGroup.Connect.Failed
- NetGroup.Connect.Rejected

The `info.group` property of the event object contains a reference to the event source (the NetGroup). The NetGroup dispatches all other events. In the server-side NetGroup class, the NetGroup dispatches all events.

For information about using groups with peer-assisted networking, see Social Media Experiences with Flash Media and RTMFP, also by Tom Krcha.

For information about the technical details behind peer-assisted networking, see P2P on the Flash Platform with RTMFP by Adobe Computer Scientist Matthew Kaufman.

View the examples

Related API Elements

flash.net.GroupSpecifier
flash.net.NetStream
flash.events.NetStatusEvent info.code values starting with "NetGroup."

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | constructor : Object A reference to the class object or constructor function for a given object instance. | Object
|  | estimatedMemberCount : Number [read-only] Specifies the estimated number of members of the group, based on local neighbor density and assuming an even distribution of group addresses. | NetGroup
|  | info : NetGroupInfo [read-only] Returns a NetGroupInfo object whose properties provide Quality of Service statistics about this NetGroup's RTMFP peer-to-peer data transport. | NetGroup
|  | localCoverageFrom : String [read-only] Specifies the start of the range of group addresses for which this node is the "nearest" and responsible. | NetGroup
|  | localCoverageTo : String [read-only] Specifies the end of the range of group addresses for which this node is the "nearest" and responsible. | NetGroup
|  | neighborCount : Number [read-only] Specifies the number of group members to which this node is directly connected. | NetGroup
|  | receiveMode : String Specifies this node's routing receive mode as one of values in the NetGroupReceiveMode enum class. | NetGroup
|  | replicationStrategy : String Specifies the object replication fetch strategy. | NetGroup

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | NetGroup(connection:NetConnection, groupspec:String) Constructs a NetGroup on the specified NetConnection object and joins it to the group specified by groupspec. | NetGroup
|  | addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. | EventDispatcher
|  | addHaveObjects(startIndex:Number, endIndex:Number):void Adds objects from startIndex through endIndex, to the set of objects this node advertises to neighbors as objects for which it fulfills requests. | NetGroup
|  | addMemberHint(peerID:String):Boolean Manually adds a record specifying that peerID is a member of the group. | NetGroup
|  | addNeighbor(peerID:String):Boolean Manually adds a neighbor by immediately connecting directly to the specified peerID, which must already be in this group. | NetGroup
|  | addWantObjects(startIndex:Number, endIndex:Number):void Adds objects from startIndex through endIndex, to the set of objects to retrieve. | NetGroup
|  | close():void Disconnect from the group and close this NetGroup. | NetGroup
|  | convertPeerIDToGroupAddress(peerID:String):String Converts a peerID to a group address suitable for use with the sendToNearest() method. | NetGroup
|  | denyRequestedObject(requestID:int):void Denies a request received in a NetStatusEvent NetGroup.Replication.Request for an object previously advertised with addHaveObjects(). | NetGroup
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | post(message:Object):String Sends a message to all members of a group. | NetGroup
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | removeHaveObjects(startIndex:Number, endIndex:Number):void Removes objects from startIndex through endIndex, from the set of objects this node advertises to neighbors as objects for which it fulfills requests. | NetGroup
|  | removeWantObjects(startIndex:Number, endIndex:Number):void Removes objects from startIndex through endIndex, from the set of objects to retrieve. | NetGroup
|  | sendToAllNeighbors(message:Object):String Sends a message to all neighbors. | NetGroup
|  | sendToNearest(message:Object, groupAddress:String):String Sends a message to the neighbor (or local node) nearest to the specified group address. | NetGroup
|  | sendToNeighbor(message:Object, sendMode:String):String Sends a message to the neighbor specified by the sendMode parameter. | NetGroup
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | toLocaleString():String Returns the string representation of this object, formatted according to locale-specific conventions. | Object
|  | toString():String Returns the string representation of the specified object. | Object
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher
|  | writeRequestedObject(requestID:int, object:Object):void Satisfies the request as received by NetStatusEvent NetGroup.Replication.Request for an object previously advertised with the addHaveObjects() method. | NetGroup

Events
Click for more information on events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active. | EventDispatcher
|  | deactivate | [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive. | EventDispatcher
|  | netStatus | Dispatched when a NetGroup object is reporting its status or error condition. | NetGroup

Property Detail

### estimatedMemberCount

property

`estimatedMemberCount:Number` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Specifies the estimated number of members of the group, based on local neighbor density and assuming an even distribution of group addresses.

Implementation
`public function get estimatedMemberCount():Number`

Related API Elements

neighborCount

### info

property

`info:NetGroupInfo` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Returns a NetGroupInfo object whose properties provide Quality of Service statistics about this NetGroup's RTMFP peer-to-peer data transport.

Implementation
`public function get info():NetGroupInfo`

Related API Elements

flash.net.NetGroupInfo

### localCoverageFrom

property

`localCoverageFrom:String` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Specifies the start of the range of group addresses for which this node is the "nearest" and responsible. The range is specified in the increasing direction along the group address ring mod 2256.

Implementation
`public function get localCoverageFrom():String`

Related API Elements

localCoverageTo
receiveMode
sendToNearest()
flash.events.NetStatusEvent.info.code="NetGroup.LocalCoverage.Notify"

### localCoverageTo

property

`localCoverageTo:String` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Specifies the end of the range of group addresses for which this node is the "nearest" and responsible. The range is specified in the increasing direction along the group address ring mod 2256.

Implementation
`public function get localCoverageTo():String`

Related API Elements

localCoverageFrom
receiveMode
sendToNearest()
flash.events.NetStatusEvent.info.code="NetGroup.LocalCoverage.Notify"

### neighborCount

property

`neighborCount:Number` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Specifies the number of group members to which this node is directly connected.

Implementation
`public function get neighborCount():Number`

Related API Elements

addNeighbor()
estimatedMemberCount
flash.events.NetStatusEvent.info.code="NetGroup.Neighbor.Connect"
flash.events.NetStatusEvent.info.code="NetGroup.Neighbor.Disconnect"

### receiveMode

property

`receiveMode:String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Specifies this node's routing receive mode as one of values in the NetGroupReceiveMode enum class.

Implementation
`public function get receiveMode():String`
`public function set receiveMode(value:String):void`

Related API Elements

localCoverageFrom
localCoverageTo
sendToNearest()
flash.net.NetGroupReceiveMode

### replicationStrategy

property

`replicationStrategy:String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Specifies the object replication fetch strategy. The value is one of the enumerated values in the NetGroupReplicationStrategy class.

Implementation
`public function get replicationStrategy():String`
`public function set replicationStrategy(value:String):void`

Related API Elements

flash.net.NetGroupReplicationStrategy
Constructor Detail

### NetGroup

()
Constructor

`public function NetGroup(connection:NetConnection, groupspec:String)`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Constructs a NetGroup on the specified NetConnection object and joins it to the group specified by `groupspec`.

In most cases, a `groupspec` has the potential for using the network uplink on the local system. When a NetStream or NetGroup object is constructed with a groupspec, Flash Player displays a Privacy Dialog. The dialog asks whether Flash Player can use the connection to share data with a user's peers. If the user clicks "Allow for this domain", the dialog is not displayed the next time the user connects to this application. If a user does not allow peer-assisted networking, all peer features within the group (posting, directed routing, and object replication, and multicast) are disabled. If permission is allowed, a NetStatusEvent is sent to the NetConnection's event listener with `NetGroup.Connect.Success` in the `code` property of the `info` object. If permission is denied, the `code` property is `NetGroup.Connect.Rejected`. Until a `NetGroup.Connect.Success` event is received, an exception is thrown if you try to call any method of the NetGroup object.

Note: When a client subscribes to a native-IP multicast stream, the security dialog is not displayed.

Parameters

| `connection:NetConnection` — A NetConnection object.
| `groupspec:String` — A string specifying the RTMFP peer-to-peer group to join, including its name, capabilities, restrictions, and the authorizations of this member. Copy
         new NetGroup(myConnection, myGroupSpecifier.groupspecWithAuthorizations());

Throws

| `ArgumentError` — The NetConnection instance is not connected.
| `Error` — The groupspec is invalid.

Related API Elements

flash.events.NetStatusEvent.info.code="NetGroup.Connect.Success"
flash.events.NetStatusEvent.info.code="NetGroup.Connect.Rejected"
flash.net.NetConnection
flash.net.GroupSpecifier
Method Detail

### addHaveObjects

()
method

`public function addHaveObjects(startIndex:Number, endIndex:Number):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Adds objects from `startIndex` through `endIndex`, to the set of objects this node advertises to neighbors as objects for which it fulfills requests. By default, the Have set is empty. Indices must be whole numbers from 0 through 9007199254740992.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

This method sends a NetStatusEvent to the NetGroup's event listener with `"NetGroup.Replication.Request"` in the `code` property of the `info` object.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `startIndex:Number` — The beginning of the range of object indices to add to the Have set.
| `endIndex:Number` — The end of the range of object indices to add to the Have set.

Throws

| `RangeError` — A number passed to this method is less than 0 or greater than 9007199254740992.

Related API Elements

removeHaveObjects()
writeRequestedObject()
denyRequestedObject()
flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"

### addMemberHint

()
method

`public function addMemberHint(peerID:String):Boolean`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Manually adds a record specifying that `peerID` is a member of the group. An immediate connection to it is attempted only if it is needed for the topology.

Parameters

| `peerID:String` — The peerID to add to the set of potential neighbors.

Returns

| `Boolean` — TRUE for success, FALSE for failure.

Related API Elements

addNeighbor()

### addNeighbor

()
method

`public function addNeighbor(peerID:String):Boolean`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Manually adds a neighbor by immediately connecting directly to the specified `peerID`, which must already be in this group. This direct connection may later be dropped if it is not needed for the topology.

Parameters

| `peerID:String` — The peerID to which to immediately connect.

Returns

| `Boolean` — TRUE for success, FALSE for failure.

Related API Elements

addMemberHint()

### addWantObjects

()
method

`public function addWantObjects(startIndex:Number, endIndex:Number):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Adds objects from `startIndex` through `endIndex`, to the set of objects to retrieve. Indices must be whole numbers from 0 through 9007199254740992. By default, the Want set is empty.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

This method sends a NetStatusEvent to the NetGroup's event listener with `NetGroup.Replication.Fetch.SendNotify` in the `info.code` property. This event is followed by an `NetGroup.Replication.Fetch.Failed` or `NetGroup.Replication.Fetch.Result` event.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `startIndex:Number` — The beginning of the range of object indices to add to the Want set.
| `endIndex:Number` — The end of the range of object indices to add to the Want set.

Throws

| `RangeError` — A number passed to this method is less than 0 or greater than 9007199254740992.

Related API Elements

removeWantObjects()
flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.SendNotify"
flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.Failed"
flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.Result"

### close

()
method

`public function close():void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Disconnect from the group and close this NetGroup. This NetGroup is not usable after calling this method.

### convertPeerIDToGroupAddress

()
method

`public function convertPeerIDToGroupAddress(peerID:String):String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Converts a peerID to a group address suitable for use with the `sendToNearest()` method.

Parameters

| `peerID:String` — The peerID to convert.

Returns

| `String` — The group address for the peerID.

Related API Elements

flash.net.NetConnection.farID
flash.net.NetConnection.nearID
flash.net.NetStream.farID
sendToNearest()

### denyRequestedObject

()
method

`public function denyRequestedObject(requestID:int):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Denies a request received in a NetStatusEvent `NetGroup.Replication.Request` for an object previously advertised with `addHaveObjects()`. The requestor can request this object again unless or until it is withdrawn from the Have set.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `requestID:int` — The request identifier as given in the `NetGroup.Replication.Request` event.

Related API Elements

addHaveObjects()
writeRequestedObject()
flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"

### post

()
method

`public function post(message:Object):String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Sends a message to all members of a group. To call this method, the `GroupSpecifier.postingEnabled` property must be `true` in the groupspec passed to the NetGroup constructor. For more information, see "Post messages to a group" in Flash Media Server Developer’s Guide.

All messages must be unique. A message that is identical to one posted earlier might not be propagated. Use a sequence number to make messages unique.

Message delivery is not ordered. Message delivery is not guaranteed.

Messages are serialized in AMF. The message can be one of the following types: an Object, an int, a Number, or a String. The message cannot be a MovieClip.

This method sends a NetStatusEvent to the NetGroup's event listener with `"NetGroup.Posting.Notify"` in the `info.code` property. The `"NetGroup.Posting.Notify"` event is dispatched to the NetGroup on both the client and the server.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `message:Object` — The message to send to all other members of the group.

Returns

| `String` — The messageID of the message if posted, or `null` on error. The messageID is the hexadecmial of the SHA256 of the raw bytes of the serialization of the message.

Related API Elements

flash.events.NetStatusEvent.info.code="NetGroup.Posting.Notify"
Example ( How to use this example )
This is a simple text chat application that uses peer-to-peer networking. The application connects over RTMFP to Flash Media Server. The server keeps the client applications' fingerprints and manages the peer group as clients connect. However, all data is sent between clients (peers) -- data is not sent back to the server.

When you run the application, you can enter any group name into the text input field. The GroupSpecifier class uses the name (along with any GroupSpecifier properties you've set) to create a string which is the perpetually unique name of the group. To connect another client to the group, that client must use the same group name. For example, if client A uses the group name "firstmesh", other clients that want to communicate with client A must also use the group name "firstmesh". If client B uses the group name "kite", it will connect successfully, but it will create a new group and won't be able to communicate with client A or anyone in the "firstmesh" group.

To run this example, add a Button, a Label, a TextInput, and a TextArea component to the Library in Flash Pro.

Copy

    package  {

        import flash.display.Sprite;
        import flash.events.TextEvent;
        import flash.events.MouseEvent;
        import flash.events.NetStatusEvent;
        import fl.events.ComponentEvent;
        import fl.controls.Label;
        import fl.controls.Button;
        import fl.controls.TextInput;
        import fl.controls.TextArea;
        import flash.text.TextFieldAutoSize;
        import flash.net.*;

        public class NetGroupPostExample extends Sprite{

            private var connectButton:Button;
            private var disconnectButton:Button;
            private var groupNameText:TextInput;
            private var userNameText:TextInput;
            private var chatText:TextInput;
            private var statusLog:TextArea;
            private var groupLabel:Label;
            private var userLabel:Label;

            private var netConnection:NetConnection = null;
            private var netGroup:NetGroup = null;
            private var sequenceNumber:uint = 0;
            private var connected:Boolean = false;
            private var joinedGroup:Boolean = false;

            private const SERVER:String = "rtmfp://fms.example.com/someapp";

            public function NetGroupPostExample() {
                DoUI();
            }

            // Writes messages to the TextArea.
            private function StatusMessage(msg:Object):void{
                statusLog.text += msg;
                statusLog.verticalScrollPosition = statusLog.textHeight;
                statusLog.validateNow();
            }

            // Handles all NetStatusEvents for the NetConnection and the NetGroup.
            // This code includes cases it doesn't handle so you can see the cases
            // and their info objects for learning purposes.
            private function NetStatusHandler(e:NetStatusEvent):void{
                StatusMessage(e.info.code + "\n");
                switch(e.info.code){
                    case "NetConnection.Connect.Success":
                        connectButton.enabled = false;
                        disconnectButton.enabled = true;
                        OnConnect();
                        break;

                    case "NetConnection.Connect.Closed":
                        OnDisconnect();
                        break;

                    case "NetGroup.Connect.Success": // e.info.group
                        OnNetGroupConnect();
                        break;

                    case "NetGroup.Connect.Rejected": // e.info.group
                    case "NetGroup.Connect.Failed": // e.info.group
                        break;

                    case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID
                        OnPosting(e.info.message);
                        break;

                    case "NetStream.MulticastStream.Reset":
                    case "NetStream.Buffer.Full":
                        break;

                    case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal
                    case "NetGroup.LocalCoverage.Notify": //
                    case "NetGroup.Neighbor.Connect": // e.info.neighbor
                    case "NetGroup.Neighbor.Disconnect": // e.info.neighbor
                    case "NetGroup.MulticastStream.PublishNotify": // e.info.name
                    case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name
                    case "NetGroup.Replication.Fetch.SendNotify": // e.info.index
                    case "NetGroup.Replication.Fetch.Failed": // e.info.index
                    case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object
                    case "NetGroup.Replication.Request": // e.info.index, e.info.requestID
                    default:
                        break;
                    }
                }
            // Creates a NetConnection to Flash Media Server if the app isn't already connected
            // and if there's a group name in the TextInput field.
            private function DoConnect(e:MouseEvent):void{
                if(!connected && (groupNameText.length > 0)){
                    StatusMessage("Connecting to \"" + SERVER + "\" ...\n");
                    netConnection = new NetConnection();
                    netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);
                    // To connect to Flash Media Server, pass the server name.
                    netConnection.connect(SERVER);
                }
                else
                {
                    StatusMessage("Enter a group name");
                }
            }

            // Called in the "NetConnection.Connect.Success" case in the NetStatusEvent handler.
            private function OnConnect():void{

                StatusMessage("Connected\n");
                connected = true;

                // Create a GroupSpecifier object to pass to the NetGroup constructor.
                // The GroupSpecifier determines the properties of the group
                var groupSpecifier:GroupSpecifier;
                groupSpecifier = new GroupSpecifier("aslrexample/" + groupNameText.text);
                groupSpecifier.postingEnabled = true;
                groupSpecifier.serverChannelEnabled = true;

                netGroup = new NetGroup(netConnection, groupSpecifier.groupspecWithAuthorizations());
                netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);

                StatusMessage("Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n");

            }

            private function OnNetGroupConnect():void{
                joinedGroup = true;
            }

            private function DoDisconnect(e:MouseEvent):void{
                if(netConnection){
                    netConnection.close();
                }
            }

            private function OnDisconnect():void{
                StatusMessage("Disconnected\n");
                netConnection = null;
                netGroup = null;
                connected = false;
                joinedGroup = false;
                connectButton.enabled = true;
                disconnectButton.enabled = false;
            }

            private function ClearChatText():void{
                chatText.text = "";
            }

            // Called when you the chatText field has focus and you press Enter.
            private function DoPost(e:ComponentEvent):void{
                if(joinedGroup){
                    var message:Object = new Object;
                    message.user = userNameText.text;
                    message.text = chatText.text;
                    message.sequence = sequenceNumber++;
                    message.sender = netConnection.nearID;

                    netGroup.post(message);
                    StatusMessage("==> " + chatText.text + "\n");
                } else {
                    StatusMessage("Click Connect before sending a chat message");
                }
                ClearChatText();
            }

            private function OnPosting(message:Object):void{
                StatusMessage("<" + message.user + "> " + message.text + "\n");
            }

            private function DoUI():void {

                groupLabel = new Label();
                groupLabel.move(20, 10);
                groupLabel.autoSize = TextFieldAutoSize.LEFT
                groupLabel.text = "Group name:"
                addChild(groupLabel);

                groupNameText = new TextInput();
                groupNameText.move(90, 10);
                groupNameText.text = "channel" + (int(Math.random() * 899) + 101);
                addChild(groupNameText);

                connectButton = new Button();
                connectButton.addEventListener(MouseEvent.CLICK, DoConnect);
                connectButton.move(205, 10);
                connectButton.label = "Connect";
                addChild(connectButton);

                disconnectButton = new Button();
                disconnectButton.addEventListener(MouseEvent.CLICK, DoDisconnect);
                disconnectButton.move(310, 10);
                disconnectButton.label = "Disconnect";
                disconnectButton.enabled = false;
                addChild(disconnectButton);

                statusLog = new TextArea();
                statusLog.move(30, 38);
                statusLog.width = 360;
                statusLog.height = 215;
                statusLog.editable = false;
                addChild(statusLog);

                userLabel = new Label();
                userLabel.move(20, 270);
                userLabel.autoSize = TextFieldAutoSize.LEFT
                userLabel.text = "User name:"
                addChild(userLabel);

                userNameText = new TextInput();
                userNameText.move(80, 270);
                userNameText.text = "user " + int(Math.random() * 65536);
                addChild(userNameText);

                chatText = new TextInput();
                chatText.addEventListener(ComponentEvent.ENTER, DoPost);
                chatText.move(185, 270);
                chatText.maxChars = 255;
                chatText.width = 215;
                addChild(chatText);

            }

            public function onPlayStatus(info:Object):void {}
            public function onMetaData(info:Object):void {}
            public function onCuePoint(info:Object):void {}
            public function onTextData(info:Object):void {}

        }

    }

### removeHaveObjects

()
method

`public function removeHaveObjects(startIndex:Number, endIndex:Number):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Removes objects from `startIndex` through `endIndex`, from the set of objects this node advertises to neighbors as objects for which it fulfills requests. Indices must be whole numbers from 0 through 9007199254740992.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `startIndex:Number` — The beginning of the range of object indices to remove from the Have set.
| `endIndex:Number` — The end of the range of object indices to remove from the Have set.

Throws

| `RangeError` — A number passed to this method is less than 0 or greater than 9007199254740992.

Related API Elements

addHaveObjects()

### removeWantObjects

()
method

`public function removeWantObjects(startIndex:Number, endIndex:Number):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Removes objects from `startIndex` through `endIndex`, from the set of objects to retrieve. Indices must be whole numbers from 0 through 9007199254740992.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `startIndex:Number` — The beginning of the range of object indices to remove from the Want set.
| `endIndex:Number` — The end of the range of object indices to remove from the Want set.

Throws

| `RangeError` — A number passed to this method is less than 0 or greater than 9007199254740992.

Related API Elements

addWantObjects()

### sendToAllNeighbors

()
method

`public function sendToAllNeighbors(message:Object):String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Sends a message to all neighbors. Returns `NetGroupSendResult.SENT` if at least one neighbor was selected.

For more information about routing messages, see "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener with `NetGroup.SendTo.Notify` in the `code` property of the `info` object.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `message:Object` — The message to send.

Returns

| `String` — A property of enumeration class NetGroupSendResult indicating the success or failure of the send.

Related API Elements

sendToNeighbor()
flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"
flash.net.NetGroupSendResult

### sendToNearest

()
method

`public function sendToNearest(message:Object, groupAddress:String):String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Sends a message to the neighbor (or local node) nearest to the specified group address. Considers neighbors from the entire ring. Returns `NetGroupSendResult.SENT` if the message was successfully sent toward its destination.

For more information about routing messages, see "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener with `NetGroup.SendTo.Notify` in the `code` property of the `info` object.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `message:Object` — The message to send.
| `groupAddress:String` — The group address toward which to route the message.

Returns

| `String` — A property of enumeration class NetGroupSendResult indicating the success or failure of the send.

Related API Elements

convertPeerIDToGroupAddress()
receiveMode
flash.net.NetGroupSendResult
flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"

### sendToNeighbor

()
method

`public function sendToNeighbor(message:Object, sendMode:String):String`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Sends a message to the neighbor specified by the `sendMode` parameter. Returns `NetGroupSendResult.SENT` if the message was successfully sent to the requested destination.

For more information about routing messages, see "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener with `NetGroup.SendTo.Notify` in the `code` property of the `info` object.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `message:Object` — The message to send.
| `sendMode:String` — A property of enumeration class NetGroupSendMode specifying the neighbor to which to send the message.

Returns

| `String` — A property of enumeration class NetGroupSendResult indicating the success or failure of the send.

Related API Elements

sendToAllNeighbors()
flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"
flash.net.NetGroupSendMode
flash.net.NetGroupSendResult

### writeRequestedObject

()
method

`public function writeRequestedObject(requestID:int, object:Object):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

Satisfies the request as received by NetStatusEvent `NetGroup.Replication.Request` for an object previously advertised with the `addHaveObjects()` method. The `object` can be any of the following: An Object, an int, a Number, and a String. The `object` cannot be a MovieClip.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the `NetGroup.Neighbor.Connect` event before calling this method.

Parameters

| `requestID:int` — The request identifier as given in the `NetGroup.Replication.Request` event.
| `object:Object` — The object corresponding to the index given in the `NetGroup.Replication.Request` event.

Related API Elements

addHaveObjects()
denyRequestedObject()
flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
Event Detail

### netStatus

Event

Event Object Type: `flash.events.NetStatusEvent`
property NetStatusEvent.type = `flash.events.NetStatusEvent.NET_STATUS`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 10.1

Dispatched when a NetGroup object is reporting its status or error condition. The `netStatus` event contains an `info` property. The `info` property is an object that contains information about the event, such as whether a connection attempt succeeded or failed.

Defines the value of the `type` property of a `netStatus` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`info` | An object with properties that describe the object's status or error condition.
`target` | The NetConnection or NetStream object reporting its status.

Related API Elements

flash.events.NetStatusEvent.info
Examples How to use this example
NetGroupExample.as
This is a simple video chat application that uses peer-to-peer networking. The application connects over RTMFP to Flash Media Server. The server keeps the client applications' fingerprints and manages the peer group as clients connect. However, all data is sent between clients (peers) -- data is not sent back to the server.

When you run the application, you can enter any group name into the text input field. The GroupSpecifier class uses the name (along with any GroupSpecifier properties you've set) to create a string which is the perpetually unique name of the group. To connect another client to the group, that client must use the same group name. For example, if client A uses the group name "firstmesh", other clients that want to communicate with client A must also use the group name "firstmesh". If client B uses the group name "kite", it will connect successfully, but it will create a new group and won't be able to communicate with client A or anyone in the "firstmesh" group.

Copy

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%" applicationComplete="OnApplicationComplete()">
        <mx:Script>
            <![CDATA[
                private var netConnection:NetConnection = null;
                private var netStream:NetStream = null;
                private var netGroup:NetGroup = null;
                private var video:Video = null;
                private var sequenceNumber:uint = 0;
                private var resizeTimer:Timer = null;

                private const SERVER:String = "rtmfp://fms.example.com/someapp";

                [Bindable] private var connected:Boolean = false;
                [Bindable] private var joinedGroup:Boolean = false;

                private function OnApplicationComplete():void
                {
                    userName.text = "user " + int(Math.random() * 65536);

                    groupName.text = "channel" + (int(Math.random() * 899) + 101);

                    resizeTimer = new Timer(2000.0);
                    resizeTimer.addEventListener(TimerEvent.TIMER, DoResizeVideo);
                    resizeTimer.start();
                }

                private function StatusMessage(msg:Object):void
                {
                    statusLog.text += msg;
                    statusLog.verticalScrollPosition = statusLog.textHeight;
                    statusLog.validateNow();
                }

                private function NetStatusHandler(e:NetStatusEvent):void
                {
                    StatusMessage(e.info.code);
                    switch(e.info.code)
                    {
                    case "NetConnection.Connect.Success":
                        OnConnect();
                        break;

                    case "NetConnection.Connect.Closed":
                    case "NetConnection.Connect.Failed":
                    case "NetConnection.Connect.Rejected":
                    case "NetConnection.Connect.AppShutdown":
                    case "NetConnection.Connect.InvalidApp":
                        OnDisconnect();
                        break;

                    case "NetStream.Connect.Success": // e.info.stream
                        OnNetStreamConnect();
                        break;

                    case "NetStream.Connect.Rejected": // e.info.stream
                    case "NetStream.Connect.Failed": // e.info.stream
                        DoDisconnect();
                        break;

                    case "NetGroup.Connect.Success": // e.info.group
                        OnNetGroupConnect();
                        break;

                    case "NetGroup.Connect.Rejected": // e.info.group
                    case "NetGroup.Connect.Failed": // e.info.group
                        DoDisconnect();
                        break;

                    case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID
                        OnPosting(e.info.message);
                        break;

                    case "NetStream.MulticastStream.Reset":
                    case "NetStream.Buffer.Full":
                        DoResizeVideo();
                        break;

                    case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal
                    case "NetGroup.LocalCoverage.Notify": //
                    case "NetGroup.Neighbor.Connect": // e.info.neighbor
                    case "NetGroup.Neighbor.Disconnect": // e.info.neighbor
                    case "NetGroup.MulticastStream.PublishNotify": // e.info.name
                    case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name
                    case "NetGroup.Replication.Fetch.SendNotify": // e.info.index
                    case "NetGroup.Replication.Fetch.Failed": // e.info.index
                    case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object
                    case "NetGroup.Replication.Request": // e.info.index, e.info.requestID
                    default:
                        break;
                    }
                }

                private function DoConnect():void
                {
                    StatusMessage("Connecting to \"" + SERVER + "\" ...\n");
                    netConnection = new NetConnection();
                    netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);
                    netConnection.connect(SERVER);
                }

                private function OnConnect():void
                {
                    var groupSpecifier:GroupSpecifier;

                    StatusMessage("Connected\n");
                    connected = true;

                    groupSpecifier = new GroupSpecifier("max2009lab/" + groupName.text);
                    groupSpecifier.multicastEnabled = true;
                    groupSpecifier.postingEnabled = true;
                    groupSpecifier.serverChannelEnabled = true;

                    netStream = new NetStream(netConnection, groupSpecifier.groupspecWithAuthorizations());
                    netStream.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);

                    netGroup = new NetGroup(netConnection, groupSpecifier.groupspecWithAuthorizations());
                    netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);

                    StatusMessage("Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n");
                }

                private function OnNetStreamConnect():void
                {
                    netStream.client = this;

                    var mic:Microphone = Microphone.getMicrophone();
                    if(mic)
                    {
                        mic.codec = SoundCodec.SPEEX;
                        mic.setSilenceLevel(0);

                        netStream.attachAudio(mic);

                        StatusMessage("got microphone\n");
                    }

                    var camera:Camera = Camera.getCamera();
                    if(camera)
                    {
                        camera.setMode(320, 240, 10);
                        camera.setQuality(30000, 0);
                        camera.setKeyFrameInterval(15);

                        videoDisplay.attachCamera(camera);
                        videoDisplay.maintainAspectRatio = true;

                        netStream.attachCamera(camera);

                        StatusMessage("got camera\n");
                    }

                    netStream.publish("stream");
                }

                private function OnNetGroupConnect():void
                {
                    joinedGroup = true;
                }

                private function DoDisconnect():void
                {
                    if(netConnection)
                        netConnection.close();
                    videoDisplay.attachCamera(null);
                }

                private function OnDisconnect():void
                {
                    StatusMessage("Disconnected\n");
                    netConnection = null;
                    netStream = null;
                    netGroup = null;
                    connected = false;
                    joinedGroup = false;
                }

                private function ClearChatText():void
                {
                    chatText.text = "";
                }

                private function DoPost():void
                {
                    var message:Object = new Object;

                    message.user = userName.text;
                    message.text = chatText.text;
                    message.sequence = sequenceNumber++;
                    message.sender = netConnection.nearID;

                    netGroup.post(message);

                    StatusMessage("==> " + chatText.text + "\n");

                    chatText.callLater(ClearChatText);
                }

                private function OnPosting(message:Object):void
                {
                    StatusMessage("<" + message.user + "> " + message.text + "\n");
                }

                private function DoResizeVideo(ignored:* = null):void
                {
                    if(video)
                    {
                        if( (0 == video.videoHeight)
                         || (0 == video.videoWidth)
                        )
                        {
                            video.height = videoDisplay.height;
                            video.width = videoDisplay.width;
                            video.x = 0;
                            video.y = 0;
                        }
                        else
                        {
                            var videoAspect:Number = Number(video.videoWidth) / Number(video.videoHeight);
                            var displayAspect:Number = Number(videoDisplay.width) / Number(videoDisplay.height);
                            var adjustFactor:Number;

                            if(videoAspect >= displayAspect) // video is wider than display
                            {
                                adjustFactor = Number(video.videoWidth) / Number(videoDisplay.width);
                                video.width = videoDisplay.width;
                                video.height = int(Number(video.videoHeight) / adjustFactor);
                                video.x = 0;
                                video.y = int((videoDisplay.height - video.height) / 2);
                            }
                            else
                            {
                                adjustFactor = Number(video.videoHeight) / Number(videoDisplay.height);
                                video.height = videoDisplay.height;
                                video.width = int(Number(video.videoWidth) / adjustFactor);
                                video.x = int((videoDisplay.width - video.width) / 2);
                                video.y = 0;
                            }
                        }
                    }
                }

                public function onPlayStatus(info:Object):void {}
                public function onMetaData(info:Object):void {}
                public function onCuePoint(info:Object):void {}
                public function onTextData(info:Object):void {}

                public function ValidateConnectAllowed(isConnected:Boolean, groupNameText:String):Boolean
                {
                    return (!isConnected) && (groupNameText.length > 0);
                }
            ]]>
        </mx:Script>

        <mx:VBox top="10" right="10" left="10" bottom="10" verticalGap="6">
            <mx:HBox width="100%">
                <mx:Text text="Group:"/>
                <mx:TextInput id="groupName" width="100%" text="default" enabled="{!connected}"/>
                <mx:Button label="Connect" click="DoConnect()" enabled="{ValidateConnectAllowed(connected, groupName.text)}" />
                <mx:Button label="Disconnect" click="DoDisconnect()" enabled="{connected}" />
            </mx:HBox>
            <mx:VideoDisplay id="videoDisplay" width="320" height="240" resize="DoResizeVideo()"/>
            <mx:TextArea id="statusLog" width="100%" height="100%"/>
            <mx:HBox width="100%">
                <mx:TextInput id="userName" width="160" />
                <mx:TextInput id="chatText" width="100%" enabled="{joinedGroup}" enter="DoPost()"/>
            </mx:HBox>
        </mx:VBox>

    </mx:Application>

© 2015 Adobe Systems Incorporated. All rights reserved.
Mon Apr 10 2017, 12:28 PM -07:00