【发布时间】:2021-02-11 13:18:01
【问题描述】:
在客户端生产者/消费者和服务器的最小 sn-p 波纹管中,我强制客户端的 send 方法出错:
import asyncio
import websockets
async def producer(websocket):
for i in range(11):
await websocket.send(i) # Invalid type, fails silently
# await websocket.send(str(i)) # Works
async def consumer(websocket):
async for msg in websocket:
i = int(msg)
print(i)
if i == 10:
return
async def echo(websocket, path):
try:
async for msg in websocket:
await websocket.send(msg)
except websockets.exceptions.ConnectionClosedOK:
print("Client disconnect.")
async def client():
async with websockets.connect("ws://localhost:8765") as websocket:
consumer_task = consumer(websocket)
producer_task = producer(websocket)
await asyncio.wait([consumer_task, producer_task])
loop = asyncio.get_event_loop()
loop.run_until_complete(websockets.serve(echo, "localhost", 8765))
loop.run_until_complete(client())
在无效类型的情况下,代码会无限期挂起,看起来就像它“默默地失败了”。 send 方法不应该因为无效的int 类型而引发异常吗(因为它只接受bytes 或str)?
【问题讨论】:
-
我对 Python 中的
async和await不太熟悉,但我猜await asyncio.wait([consumer_task, producer_task])将首先等待consumer_task完成,然后再传播引发的任何异常异步来自producer_task。 -
如果我正在查看正确的代码here,那么在传递错误类型的
data时会引发异常。 -
确实,我将
return_when=asyncio.FIRST_EXCEPTION作为asyncio.wait的参数,至少现在代码不会无限期挂起。我现在正试图弄清楚如何从未来重新引发异常(尽管我猜它应该在默认情况下重新引发)。
标签: python websocket python-asyncio