Menu Search

1.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 1.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:  (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
	connection.close()  (7)


Establishes the connection with the messaging broker.


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


Creates a receiver that receives messages from the given address.


Creates a sender that sends to the given address.


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


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


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