Python Websockets:客户端recv上的无限锁定

时间:2017-07-30 19:44:37

标签: python websocket python-3.6

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

使用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())

在执行期间,服务器正在做他所期望的事情:

  • 等待客户端消息
  • 队列'Hello $message'
  • 出局
  • 将出站的消息发送回发件人

客户端确实等待服务器响应:

  • 等待用户输入
  • 将其发送至服务器
  • 等待来自服务器的答案&lt; - 无限期地坚持
  • 打印&amp;环

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

服务器

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
_

我错过了什么?

1 个答案:

答案 0 :(得分:4)

服务器端,您在await行上错过了websocket.send(message)

要查找这些错误,请使用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