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, which maintains the state of all interactions with the messaging broker, and manages senders and receivers.

(4)

Creates a receiver that reads from the given address.

(3)

Creates a sender that sends to the given address.

(5)

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

(6)

Acknowledges messages that have been read. To guarantee delivery, a message remains on the messaging broker until it is acknowledged by a client. session.acknowledge() acknowledges all unacknowledged messages for the given session—this allows acknowledgements to be batched, which is more efficient than acknowledging messages individually.

(7)

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