4.2. 接收消息
这个客户端程序使用 <connection-url>
连接到服务器,为源 <address>
创建一个接收器,并在其终止或到达 <count>
信息前接收信息。
示例:接收消息
from __future__ import print_function import sys from proton.handlers import MessagingHandler from proton.reactor import Container class ReceiveHandler(MessagingHandler): def __init__(self, conn_url, address, desired): super(ReceiveHandler, self).__init__() self.conn_url = conn_url self.address = address self.desired = desired self.received = 0 def on_start(self, event): conn = event.container.connect(self.conn_url) # To connect with a user and password: # conn = event.container.connect(self.conn_url, user="<user>", password="<password>") event.container.create_receiver(conn, self.address) def on_link_opened(self, event): print("RECEIVE: Created receiver for source address '{0}'".format (self.address)) def on_message(self, event): message = event.message print("RECEIVE: Received message '{0}'".format(message.body)) self.received += 1 if self.received == self.desired: event.receiver.close() event.connection.close() def main(): try: conn_url, address = sys.argv[1:3] except ValueError: sys.exit("Usage: receive.py <connection-url> <address> [<message-count>]") try: desired = int(sys.argv[3]) except (IndexError, ValueError): desired = 0 handler = ReceiveHandler(conn_url, address, desired) container = Container(handler) container.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass
运行示例
要运行示例程序,将其复制到本地文件中并使用 python
命令调用它。如需更多信息,请参阅 第 3 章 入门。
$ python receive.py amqp://localhost queue1