Python Websockets : 无限锁定客户端 recv.



我正在学习如何将 python 3.6 的websockets包与asyncio一起使用。

使用 Websockets 入门示例,以下是我的服务器和客户端代码(两者都使用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'
  • 取消排队
  • 将取消排队的消息发送回发件人

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

  • 等待用户输入
  • 将其发送到服务器
  • 等待服务器应答 <-- 无限期保留
  • 打印它和循环

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

服务器

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

最新更新