This article is compatible with the latest version of Silverlight.
A completely new feature in Silverlight is the ability to establish a local connection between loaded Silverlight applications. In this context connection means exchanging messages and it happens only on the client side – no server roundtrip occurs.
This is useful mainly in scenarios where you need a communication channel between multiple applications hosted on single page (like navigation and other controls) and integration between out-of-browser applications. The connection is highly configurable and is not limited only to applications living only on one page or domain.
Let’s start with a demo which demonstrates a communication between two Silverlight applications hosted on a single page.
Content
Download source code
In general what we need is a sender application and a receiver application. In the demo above Navigation is the sender, Content is the receiver.
Sender - LocalMessageSender
LocalMessageSender class is defined in System.Windows.Messaging namespace and it is used to send message to local listeners.
In order to send a message we need the receiver’s name and optionally the receiver’s domain. We can send the message either to a specific domain(pass domain name as receiverDomain) or without specifying a domain scope(pass System.Windows.Messaging.LocalMessageSender.Global).
LocalMessageSender sender = new LocalMessageSender(
"Receiver Name",
System.Windows.Messaging.LocalMessageSender.Global );
sender.SendCompleted += ( object sender, SendCompletedEventArgs e ) =>
{
...
};
sender.SendAsync( "Message" );
Using SendAsync method we send the message. After the message is sent the SendCompleted event is fired. If the method didn’t succeed a SendFailedException is thrown which can be obtained from the SendCompletedEventArgs.
Receiver – LocalMessageReceiver
The receiver is just as simple as the sender. You can specify a list of allowed sender domains, i.e. from which domains you want to receive messages.
List<string> allowedSenderDomains = new List<string>();
allowedSenderDomains.Add( "silverlightshow.net" );
allowedSenderDomains.Add( "www.silverlightshow.net" );
allowedSenderDomains.Add( "localhost" );
LocalMessageReceiver receiver = new LocalMessageReceiver(
"Receiver Name",
ReceiverNameScope.Global,
allowedSenderDomains );
receiver.MessageReceived += ( object sender, MessageReceivedEventArgs e ) =>
{
...
};
receiver.Listen();
Using Listen we start waiting for a message. MessageReceived event is fired once a message, sent to “Receiver Name”, is received. In MessageReceivedEventArgs there is a property Response which you can use to immediately send a response to the sender.