Debian Codegraph @

python/examples/client.py

raw
1 #!/usr/bin/env python3
2 #
3 # Licensed to the Apache Software Foundation (ASF) under one
4 # or more contributor license agreements. See the NOTICE file
5 # distributed with this work for additional information
6 # regarding copyright ownership. The ASF licenses this file
7 # to you under the Apache License, Version 2.0 (the
8 # "License"); you may not use this file except in compliance
9 # with the License. You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing,
14 # software distributed under the License is distributed on an
15 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 # KIND, either express or implied. See the License for the
17 # specific language governing permissions and limitations
18 # under the License.
19 #
20
21 import optparse
22 from proton import Message
23 from proton.handlers import MessagingHandler
24 from proton.reactor import Container
25
26
27 class Client(MessagingHandler):
28 def __init__(self, url, requests):
29 super(Client, self).__init__()
30 self.url = url
31 self.requests = requests
32
33 def on_start(self, event):
34 self.sender = event.container.create_sender(self.url)
35 self.receiver = event.container.create_receiver(self.sender.connection, None, dynamic=True)
36
37 def next_request(self):
38 if self.receiver.remote_source.address:
39 req = Message(reply_to=self.receiver.remote_source.address, body=self.requests[0])
40 self.sender.send(req)
41
42 def on_link_opened(self, event):
43 if event.receiver == self.receiver:
44 self.next_request()
45
46 def on_message(self, event):
47 print("%s => %s" % (self.requests.pop(0), event.message.body))
48 if self.requests:
49 self.next_request()
50 else:
51 event.connection.close()
52
53
54 REQUESTS = ["Twas brillig, and the slithy toves",
55 "Did gire and gymble in the wabe.",
56 "All mimsy were the borogroves,",
57 "And the mome raths outgrabe."]
58
59 parser = optparse.OptionParser(usage="usage: %prog [options]",
60 description="Send requests to the supplied address and print responses.")
61 parser.add_option("-a", "--address", default="localhost:5672/examples",
62 help="address to which messages are sent (default %default)")
63 opts, args = parser.parse_args()
64
65 Container(Client(opts.address, args or REQUESTS)).run()