Thursday, September 24, 2009

MSMQ - Connecting Remote MSMQ

Connecting to remote MSMQ can be an easy task, yet, it can be a difficult one.

First, if you want to connect to a remote MSMQ, you have to define the queue name with FormatName

For machine name, use FormatName:Direct=OS:mymachine\private$\remoteQueue

For IP, use FormatName:Direct=TCP:10.10.10.1\private$\remoteQueue
The above is for Private Queue. If you want to connect to a Public queue, just remove private$ from the above string. Also, please note that you cannot use IP address on OS and vice versa.

Now, you are ready to program. All you need is 3 lines for send and 5 lines for receive

Note: the example is for private queue. For public queue, remove private$ from queuePath

C# code for Send



String queuePath = "FormatName:Direct=TCP:10.10.10.1\\private$\\remoteQueue";

MessageQueue mq = new MessageQueue(queuePath);

mq.Send(txtMsg.Text);




C# code for Receive



String queuePath = "FormatName:Direct=TCP:10.10.10.1\\private$\\remoteQueue";

MessageQueue mq = new MessageQueue(queuePath);

System.Messaging.Message msg = mq.Receive();

msg.Formatter = new XmlMessageFormatter(new string[] { "System.String" });

Console.Write("received message: " + msg.Body);




Note:

1. For receive, the above code perform receive synchronously. Thus, it will suspend the thread and only return when a queue message is received

2. Programming with MSMQ become tough and waste a lot of time if you did not read the API correctly. For example, MessageQueue.Exist(). This method only work for local queue. It will fail on all remote/Direct FormatName where machine in Workgroup mode. Please read http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue_methods.aspx carefully.

3 comments:

  1. It doesn't work for me when I tried. An exception: 'Format name is invalid.' is appeared.
    Please give me some tips. Thank you.

    ReplyDelete
  2. Check your format. That is the most headache part of MSMQ

    See http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.formatname(VS.71).aspx

    ReplyDelete
  3. Do make sure the MQ is created before receiving it. Meaning to say, check for the existence of the MQ and if it does not exist, create it (programmaticaly) on application start up.

    FYI, Message Queuing is not installed by default. You have to add the Windows optional Component yourself.

    ReplyDelete

Windows 7 - STOP 0x0000007B (0xFFFFF880009A97E8 0xFFFFFFFFC0000034 0x0000000000 0x0000000000)

If you encounter STOP 0x0000007B (0xFFFFF880009A97E8 0xFFFFFFFFC0000034 0x0000000000 0x0000000000) blue screen of death. This is very like...