Message Queuing

From IronPython Cookbook

Revision as of 14:22, 9 June 2007 by MichaelFoord (Talk | contribs)

From Nauman Leghari.

Message Queuing 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.

Installing Message Queuing

(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 from the original queue (we will receive it as bytes and decode it back to text):

from System import Array, Byte
from System.Text import Encoding

# This blocks until it receives
message = queue.Receive()

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

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

This prints:

<?xml version="1.0"?>
<string>Hello from IronPython</string>


Back to Contents.

TOOLBOX
LANGUAGES