Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. # THIS IS txconsumer.py
  2.  
  3. from twisted.internet.defer import inlineCallbacks
  4. from twisted.internet import reactor
  5. from twisted.internet.protocol import ClientCreator
  6. from txamqp.protocol import AMQClient
  7. from txamqp.client import TwistedDelegate
  8. import txamqp.spec
  9.  
  10. @inlineCallbacks
  11. def gotConnection(conn, username, password):
  12.     print "Connected to broker."
  13.     yield conn.authenticate(username, password)
  14.  
  15.     print "Authenticated. Ready to receive messages"
  16.     chan = yield conn.channel(1)
  17.     yield chan.channel_open()
  18.  
  19.     yield chan.queue_declare(queue="chatrooms", durable=True, exclusive=False, auto_delete=False)
  20.     yield chan.exchange_declare(exchange="chatservice", type="direct", durable=True, auto_delete=False)
  21.  
  22.     yield chan.queue_bind(queue="chatrooms", exchange="chatservice", routing_key="txamqp_chatroom")
  23.  
  24.     yield chan.basic_consume(queue='chatrooms', no_ack=True, consumer_tag="testtag")
  25.  
  26.     queue = yield conn.queue("testtag")
  27.  
  28.     while True:
  29.         msg = yield queue.get()
  30.         print 'Received: ' + msg.content.body + ' from channel #' + str(chan.id)
  31.         if msg.content.body == "STOP":
  32.             break
  33.  
  34.     yield chan.basic_cancel("testtag")
  35.  
  36.     yield chan.channel_close()
  37.  
  38.     chan0 = yield conn.channel(0)
  39.  
  40.     yield chan0.connection_close()
  41.  
  42.     reactor.stop()
  43.  
  44.  
  45. if __name__ == "__main__":
  46.     import sys
  47.     if len(sys.argv) < 7:
  48.         print "%s host port vhost username password path_to_spec" % sys.argv[0]
  49.         print "e.g. %s localhost 5672 / guest guest ../../specs/standard/amqp0-8.xml" % sys.argv[0]
  50.         sys.exit(1)
  51.  
  52.     host = sys.argv[1]
  53.     port = int(sys.argv[2])
  54.     vhost = sys.argv[3]
  55.     username = sys.argv[4]
  56.     password = sys.argv[5]
  57.  
  58.     spec = txamqp.spec.load(sys.argv[6])
  59.  
  60.     delegate = TwistedDelegate()
  61.  
  62.     d = ClientCreator(reactor, AMQClient, delegate=delegate, vhost=vhost,
  63.         spec=spec).connectTCP(host, port)
  64.  
  65.     d.addCallback(gotConnection, username, password)
  66.  
  67.     reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement