我目前正在努力使用Flask,RabbitMQ和Python网络套接字实现简单的聊天。
我有3个Docker容器用于我的背部,前部和一个运作良好的RabbitMQ映像。并行地,我执行一个脚本,其中使用RabbitMQ队列中的消息,并将其通过回调中的websocket发送到前端(下面的代码)。
尝试几次后,ws.send(message)
中的send_websocket()
仍然无法正常工作。
我的错误是:RuntimeWarning: coroutine 'WebSocketCommonProtocol.send' was never awaited ws.send(message)
当我在async
中添加await
和send_websocket()
关键字时,错误是RuntimeWarning: coroutine 'send_websocket' was never awaited send_websocket(body)
我尝试使用asyncio.run(ws.send(message))
,但是连接没有发送消息就关闭了。
我尝试使用asyncio.create_task(ws.send(message))
,但得到RuntimeError: no running event loop
和RuntimeWarning: coroutine 'WebSocketCommonProtocol.send' was never awaited
。我需要创建一个循环吗?
import pika, threading
import asyncio
import websockets
global_ws_array = []
#### RabbitMQ callback
def send_websocket(message):
for ws in global_ws_array:
print("Send message", message)
ws.send(message)
#### Websocket callback
async def ws_handler(websocket, path):
global_ws_array.append(websocket)
print("Length array", len(global_ws_array))
#### RabbitMQ launch
def receive_message_queue(queue_name, url="amqp://rabbitmq:rabbitmq@localhost/%2f"):
connection = pika.BlockingConnection(pika.URLParameters(url))
channel = connection.channel()
channel.queue_declare(queue=queue_name, durable=True)
def callback(ch, method, properties, body):
send_websocket(body)
channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
mq_recieve_thread = threading.Thread(target=channel.start_consuming)
mq_recieve_thread.start()
receive_message_queue("chat")
#### Websocket server launch
start_server = websockets.serve(ws_handler, "0.0.0.0", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
您知道我的错误来自哪里吗?谢谢您的帮助!
答案 0 :(得分:0)
在从 WebSockets 发送数据时尝试使用 await
。它将期望等待并使方法成为 async
。
#### RabbitMQ callback
async def send_websocket(message):
for ws in global_ws_array:
print("Send message", message)
await ws.send(message)