Message Queuing

From Nauman Leghari.

Message Queuing (MSMQ) is a form of inter-process communication. It allows ''allows applications running at different times to communicate across heterogeneous networks and systems that might be temporarily offline. Applications send, receive, or peek (read without removing) messages from queues''.

Message Queuing is an optional component of Windows XP and Windows 2000/NT. In order to use it, it must be installed. To do this you go to the control panel, select add or remove programs, and then Add/Remove Windows Components.



(On my system this didn't require the original install disks to do.)

This example uses the MessageQueue class from the System.Messaging namespace.

Messages are sent (and received) as a Message.

Launch an IronPython console. In this interpreter we will setup the queue and get ready to receive the message: import clr clr.AddReference('System.Messaging') from System.Messaging import MessageQueue

ourQueue = '.\\private$\\myqueue' if not MessageQueue.Exists(ourQueue): queue = MessageQueue.Create(ourQueue) else: queue = MessageQueue(ourQueue)

In a separate console, we will access the queue and send a message: import clr clr.AddReference('System.Messaging') from System.Messaging import MessageQueue

ourQueue = '.\\private$\\myqueue' queue = MessageQueue(ourQueue) queue.Send('Hello from IronPython')

We're now ready to receive this message back in the original console (we will receive it as bytes and decode it back to text): from System import Array, Byte from System.Text import Encoding

message = queue.Receive
 * 1) This blocks until it receives

messageStream = message.BodyStream byteArray = Array.CreateInstance(Byte, messageStream.Length) messageStream.Read(byteArray, 0, messageStream.Length)

messageText = Encoding.UTF8.GetString(byteArray) print messageText

This prints:  Hello from IronPython

Using XmlMessageFormatter and BinaryMessageFormatter, you can send and receive messages (including files/images etc) without having to deal with the XML de-serialization yourself.

Back to Contents.