Menu Search

2.2. A Simple Messaging Program in Python

The following Python program shows how to create a connection, create a session, send messages using a sender, and receive messages using a receiver.

Example 2.2. "Hello world!" in Python

	import sys
	from qpid.messaging import *

	broker =  "localhost:5672" if len(sys.argv)<2 else sys.argv[1]
	address = "amq.topic" if len(sys.argv)<3 else sys.argv[2]

	connection = Connection(broker)

	try:
	connection.open()  (1)
	session = connection.session()   (2)

	sender = session.sender(address)  (3)
	receiver = session.receiver(address)  (4)

	sender.send(Message("Hello world!"));

	message = receiver.fetch(timeout=1)  (5)
	print message.content
	session.acknowledge() (6)

	except MessagingError,m:
	print m
	finally:
	connection.close()  (7)
	

(1)

Establishes the connection with the messaging broker.

(2)

Creates a session object on which messages will be sent and received.

(4)

Creates a receiver that receives messages from the given address.

(3)

Creates a sender that sends to the given address.

(5)

Receives the next message. The duration is optional, if omitted, will wait indefinitely for the next message.

(6)

Acknowledges receipt of all fetched messages on the session. This informs the broker that the messages were transfered and processed by the client successfully.

(7)

Closes the connection, all sessions managed by the connection, and all senders and receivers managed by each session.