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消息无法通过。
答案 0 :(得分:1)
尝试使用此代码:
https://github.com/Gsantomaggio/rabbitmqexample/tree/master/webSocketPython
Sub testifthenelse(bQuit As Boolean)
Dim s As String
s = "Do you want to quit?"
If MsgBox(s, vbYesNo, "Quite?") = vbYes Then
bQuit = True
Else
bQuit = False
End If
End Sub
和
def threaded_rmq():
channel.queue_declare(queue="my_queue")
logging.info('consumer ready, on my_queue')
channel.basic_consume(consumer_callback, queue="my_queue", no_ack=True)
channel.start_consuming()