【发布时间】:2016-12-16 09:09:49
【问题描述】:
class WSHandler(tornado.websocket.WebSocketHandler):
clients = []
def open(self, name):
# WSHandler.clients.append(self)
# liveWebSockets.add(self)
self.id = name
self.clients.append(self)
# self.application.pc.add_event_listener(self)
print 'new connection'
def on_message(self, message):
print 'message received: %s' % message
# Reverse Message and send it back
print 'sending back message: %s' % message[::-1]
# pika sending message
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
# clients.append(self)
channel.queue_declare(queue='hello')
# print dir(self)
message_rabbit_mq = {
'web_socket': self.id,
'message': message
}
message_rabbit_mq = json.dumps(message_rabbit_mq)
channel.basic_publish(exchange='',
routing_key='hello',
body=message_rabbit_mq)
connection.close()
self.rabbit_connect()
# def rabbit_connect():
# pika receving message
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
self.write_message(body)
time.sleep(4)
body_obj = json.loads(body)
if 'message' in body:
if body_obj['message'] == "crack":
channel.stop_consuming()
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
self.write_message("closed reference")
上面代码中的问题是
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
self.write_message(body)
time.sleep(4)
body_obj = json.loads(body)
if 'message' in body:
if body_obj['message'] == "crack":
channel.stop_consuming()
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
以上部分阻塞了 on_message 函数中的其余逻辑。我如何让上述部分与其余逻辑异步运行? 这使得来自客户端的进一步 websocket 消息无法处理。
【问题讨论】:
标签: python rabbitmq tornado pika