Python Websockets:无限锁定客户端接收

Python Websockets : infinite lock on client recv

我正在学习如何将 websockets 包用于 python 3.6 和 asyncio

使用 Websockets Getting Started 示例,这是我的服务器和客户端代码(都 运行 在两个单独的控制台中使用 python <script>

wsserver.py

import asyncio

import websockets

msg_queue = asyncio.Queue()


async def consumer_handler(websocket):
    global msg_queue
    while True:
        message = await websocket.recv()
        print("Received message {}".format(message))
        await msg_queue.put("Hello {}".format(message))
        print("Message queued")


async def producer_handler(websocket):
    global msg_queue
    while True:
        print("Waiting for message in queue")
        message = await msg_queue.get()
        print("Poped message {}".format(message))
        websocket.send(message)
        print("Message '{}' sent".format(message))


async def handler(websocket, path):
    print("Got a new connection...")
    consumer_task = asyncio.ensure_future(consumer_handler(websocket))
    producer_task = asyncio.ensure_future(producer_handler(websocket))

    done, pending = await asyncio.wait([consumer_task, producer_task]
                                       , return_when=asyncio.FIRST_COMPLETED)
    print("Connection closed, canceling pending tasks")
    for task in pending:
        task.cancel()


start_server = websockets.serve(handler, 'localhost', 5555)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

wsclient.py

import asyncio
import websockets

async def repl():
    async with websockets.connect('ws://localhost:5555') as websocket:
        while True:
            name = input("\nWhat's your name? ")

            await websocket.send(name)
            print("Message sent! Waiting for server answer")

            greeting = await websocket.recv()
            # never goes here
            print("> {}".format(greeting))

asyncio.get_event_loop().run_until_complete(repl())

在执行过程中,服务器正在做他期望的事情:

客户端一直工作到等待服务器响应为止:

以下是执行的控制台输出:

服务器

Got a new connection...
Waiting for message in queue
Received message TestName
Message queued
Poped message Hello TestName 
Message 'Hello TestName' sent 
Waiting for message in queue

客户

What's your name? TestName
Message sent! Waiting for server answer
_

我错过了什么?

服务器端,您在 websocket.send(message) 行缺少 await

要查找此类错误,请使用 PYTHONASYNCIODEBUG 环境变量启动您的程序,例如:PYTHONASYNCIODEBUG=1 python3 wsserver.py 打印:

<CoroWrapper WebSocketCommonProtocol.send() running at […]/site-packages/websockets/protocol.py:301, created at wsserver.py:23> was never yielded from