不接收来自Javascript客户端的消息

时间:2019-06-09 15:56:27

标签: python websocket

我正在基于websockets创建服务器,并使用了https://websockets.readthedocs.io/en/stable/intro.html中的指南。当我同时启用两个处理程序时,由producer_handler生成的消息可以到达Web客户端,但是服务器不会接收到Web客户端发送的消息。该代码永远不会从websocket.recv()返回。如果我禁用了(注释掉了)producer_handler,则Web客户端发送的消息可以正常接收。我在Raspberry Pi 3上运行Python 3.5.3。我在做什么错了?

import sys
import time
import asyncio
import websockets

print(sys.version)

async def consumer(message):
    print(message)

async def producer():
    time.sleep(2)
    return "log: This is a test"


async def consumer_handler(websocket, path):
    while True:
        message = await websocket.recv()
        print("Consumer handler message received")
        await consumer(message)

async def producer_handler(websocket, path):
    time.sleep(10)
    while True:
        message = await producer()
        await websocket.send(message)

async def handler(websocket, path):
    consumer_task = asyncio.ensure_future(
        consumer_handler(websocket, path))
    producer_task = asyncio.ensure_future(
        producer_handler(websocket, path))
    done, pending = await asyncio.wait(
        [consumer_task, producer_task],
        return_when=asyncio.FIRST_COMPLETED,
    )
    for task in pending:
        task.cancel()

asyncio.get_event_loop().run_until_complete(
    websockets.serve(handler, 'localhost', 8765))
asyncio.get_event_loop().run_forever()

0 个答案:

没有答案