65.9K
CodeProject is changing. Read more.
Home

Local Messaging in Silverlight

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Nov 19, 2009

MIT
viewsIcon

17651

downloadIcon

161

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.