A message channel provides a one-way data-passing link
between two workers. Using a MessageChannel object to pass data
between workers has one key advantage. When you send a message (an
object) using a message channel, the MessageChannel object dispatches
a
channelMessage
event. Code in the receiving worker
can listen for that event to know when data is available. That way
the receiving worker doesn’t need to continuously check for data
updates.
A message channel is associated with only two workers, a sender
and a receiver. To create a MessageChannel object, call the sending
Worker object’s
createMessageChannel()
method,
passing the receiving worker as an argument:
// In the sending worker swf
var sendChannel:MessageChannel;
sendChannel = Worker.current.createMessageChannel(receivingWorker);
Both workers need to have access to the MessageChannel object.
The simplest way to do this is to pass the MessageChannel object
using the
setSharedProperty()
method:
receivingWorker.setSharedProperty("incomingChannel", sendChannel);
In the receiving worker, register a listener for the MessageChannel
object’s
channelMessage
event. This event is dispatched
when the sending worker sends data through the message channel.
// In the receiving worker swf
var incomingChannel:MessageChannel;
incomingChannel = Worker.current.getSharedProperty("incomingChannel");
incomingChannel.addEventListener(Event.CHANNEL_MESSAGE, handleIncomingMessage);
To actually send data, in the sending worker call the MessageChannel
object’s
send()
method:
// In the sending worker swf
sendChannel.send("This is a message");
In the receiving worker, the MessageChannel calls the
channelMessage
event handler.
The receiving worker can then get the data by calling the MessageChannel
object’s
receive()
method.
private function handleIncomingMessage(event:Event):void
{
var message:String = incomingChannel.receive() as String;
}
The object returned by the receive method has the same data type
as the object that was passed in to the
send()
method.
The received object is a copy of the object passed in by the sender
and not a reference to the object in the sending worker, unless
it is one of a few data types, as described in
Shared references and copied values
.