Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Local Messaging in Silverlight

0.00/5 (No votes)
18 Nov 2009 1  
Communicating with Silverlight applications locally.

Introduction

The new Silverlight 3.0 allows plug-ins to be exposed as a listener, with a specific name, that may be addressed by other plug-in instances knowing this name. If you have ever used named-pipes for inter-process communications, you may found that Local Connections are very similar. There are two classes you may use to establish a connection: LocalMessageReceiver and LocalMessageSender.

Using the Code

Here is a sample for LocalMessageSender:

Dim lms As System.Windows.Messaging.LocalMessageSender = _
  New System.Windows.Messaging.LocalMessageSender("receiveParent", _
  System.Windows.Messaging.LocalMessageSender.Global)
'you can restrict sending messages to any domain

Here is a sample for LocalMessageReceiver:

Dim lmr As System.Windows.Messaging.LocalMessageReceiver = _
     New System.Windows.Messaging.LocalMessageReceiver("receiveParent", _ 
                        Messaging.ReceiverNameScope.Global,_ 
                        System.Windows.Messaging.LocalMessageReceiver.AnyDomain)
AddHandler lmr.MessageReceived,AddressOf HandleMessage
'attach message receive handler

'Listen global,receive any domain 
Try
    lmr.Listen()
Catch ex As System.Windows.Messaging.ListenFailedException
    'if there is already a receiver with the name 'receiveParent'
    'LocalMessageReceiver  throws exception
End Try

Sending a message:

lms.SendAsync("Message To Send")

Receiving a message:

Private Sub HandleMessage(ByVal sender as Object, _
        Byval e as ByVal e As System.Windows.Messaging.MessageReceivedEventArgs)
    'process message...
End Sub

You can send messages in XML or JSON format if your message is in a complex format.

Remember that the maximum message length is 40 KB. (Reference.)

Points of Interest

I discovered a listener use a unique receiver name. When you use a listener with the same receiver name, it throws an exception. If we want to make our application single instance on the computer, this could help us!

History

  • 2009.11.19 - First release.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here