UNIPacket – Standardize NetGroup, NetStream Raw Messages

UNIPacket and UNIPacketHeader classes is my attempt to standardize communication within NetStream and NetGroup communication. While both Net* classes enables you to send any raw data between two instances of flash, you should carefully handle incomming messages. Imagine you are willing to send additional info with your message (sender, id etc.). That is where UNIPacket classes comes into scene, both are very simple and able to selfcreate from incomming object.

UNIPacket contains only two variables: header:UNIPacketHeader and data:* (holds the actual data being sent).

UNIPacketHeader is dynamic class with prepared variables: id:uint (numeric identificator of message), hash:String (string identificator of message), sender:String (use for sender identification).

Preparing UNIPacket:

var header:UNIPacketHeader = new UNIPacketHeader();
header.sender = netGroup.convertPeerIDToGroupAddress(netConnection.nearID);
header.id = uint(Math.random() * uint.MAX_VALUE);
header.someDynamicVariable = "XYZ";
var data:String = "Hallo world"
var messageOut:UNIPacket = new UNIPacket(header, data);

Usage with NetStream:

// SENDER:
var netStream:NetStream = new NetStream(...);
netStream.send("onNotify", messageOut);

// RECEIVER:
var messageIn:UNIPacket;
var netStream:NetStream = new NetStream(...);
netStream.client = {
    onNotify: function(data:Object):void
    {
        messageIn = UNIPacket.create(data);
        messageIn.data;
        messageIn.header.sender;
        messageIn.header.id;
        messageIn.header.someDynamicVariable;
    }
}

Usage with NetGroup:

// SENDER:
var groupSpecifier:GroupSpecifier = new GroupSpecifier("somegruop");
groupSpecifier.serverChannelEnabled = true;
groupSpecifier.multicastEnabled = true;
groupSpecifier.ipMulticastMemberUpdatesEnabled = true;
groupSpecifier.postingEnabled = true;
var groupspec:String = groupSpecifier.groupspecWithAuthorizations();
var netGroup:NetGroup = new NetGroup(netConnection, groupspec);
...
netGroup.post(messageOut);

// RECEIVER:
var messageIn:UNIPacket;
var netGroup:NetGroup = new NetGroup(...);
netGroup.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
function onNetStatus(event:NetStatusEvent):void
{
    switch(event.info.code)
    {
        case "NetGroup.Posting.Notify":
            messageIn = UNIPacket.create(event.info.message);
            messageIn.data;
            messageIn.header.sender;
            messageIn.header.id;
            messageIn.header.someDynamicVariable;
            break;
    }
}

Leave a comment

Please be polite and on topic. Your e-mail will never be published.