Search code examples
c#.netvb.netmsmq

How do I send/receive multicast messages using MSMQ?


Can someone please help me find some sample code to SEND and RECEIVE Multicast messages using MSMQ using any .NET language of your choice. I have searched around and kind of see the send being:

MessaegQueue topic = new MessageQueue("formatname:multicast=234.1.1.1:8081")
topic.Send("Hello out there")

I tried to do the same idea with Receive:

MessageQueue topic = new MessageQueue("formatname:multicast=234.1.1.1:8081")
topic.Receive();

but I get nothing. Can anyone show some sample code on how to receive multicast messages? or am I sending them wrong?


Solution

  • So I figured it out.

    To send a multicast message:

    MessageQueue topic = new MessageQueue("formatname:multicast=234.1.1.1:8081")
    topic.Send("Hello out there")
    

    To receive a multicast message:

    It is a little tricky because you can't subscribe to the multicast address. What you need to do is create a queue, probably best to create a private queue that will be attached to the multicast address you want to monitor and then listen to the private queue you created INSTEAD of the multicast address. Something like this:

      Dim privMulticastQueue As String = GetPrivateQueueForMulticastAddress("formatname:multicast=234.1.1.1:8081")
      Dim msgq as MessageQueue = GetMessageQueue(privMulticastQueue)
      msgq.MulticastAddress = GetMulticastAddress(destination)
      msgq.Label = "Private Queue for receiving messages from: " & destination
      msgq.Receive()
    

    And some supporting methods (probably there is a better way to write them so feel free to correct but this is my first crack at it):

     Private Function GetPrivateQueueForMulticastAddress(ByVal dest As String) As String
        Dim privateQ As String = GetMulticastAddress(dest).Replace(".", "_").Replace(":", "_")
        Return ".\Private$\" & privateQ
     End Function
    
    Private Function GetMulticastAddress(ByVal dest As String) As String
        Return dest.Split("=")(1)
    End Function
    
    Private Function GetMessageQueue(ByVal dest As String) As MessageQueue   
          Try
               If Not MessageQueue.Exists(dest) Then
                 MessageQueue.Create(dest)
                End If
    
                Dim msgq As MessageQueue = New MessageQueue(dest)
                Return msgq
          Catch ex As Exception
                Throw New EMGException("Failed while trying to use destination: " & dest, ex)
          End Try
    
    End Function