带生产者和消费者的Python websocket
我正在尝试创建一个websocket服务器,它将接受来自一个客户端(比如a)的消息并将其存储在队列中。然后还有另一个客户端B,它将连接到websocket以读取队列弹出的消息 为了识别客户端,我正在使用不同的路径编辑请求url。下面是我的代码:带生产者和消费者的Python websocket,python,websocket,Python,Websocket,我正在尝试创建一个websocket服务器,它将接受来自一个客户端(比如a)的消息并将其存储在队列中。然后还有另一个客户端B,它将连接到websocket以读取队列弹出的消息 为了识别客户端,我正在使用不同的路径编辑请求url。下面是我的代码: import asyncio import websockets from queue import Queue q = Queue(maxsize = 10) async def consumer_handler(websocket, path):
import asyncio
import websockets
from queue import Queue
q = Queue(maxsize = 10)
async def consumer_handler(websocket, path):
if path=="/":
async for message in websocket:
await consumer(message)
async def producer_handler(websocket, path):
if path=="/read":
while True:
message = await producer()
await websocket.send(message)
async def consumer(message):
q.put(message)
async def producer():
return q.get()
async def handler(websocket, path):
loop = asyncio.get_event_loop()
producer_task = loop.create_task(producer_handler(websocket, path))
consumer_task = loop.create_task(consumer_handler(websocket, path))
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
它不接受消息,客户端B也无法读取消息
没有websocket.recv()行,我不明白它是如何获得消息的
我同意文档中生产者、消费者和处理者方法的定义
另外,当尝试从客户端B重新打开连接时,它将挂起处于“打开”状态
我是websocket编码新手,请指导我哪里出了问题
谢谢