【发布时间】:2021-07-26 09:09:38
【问题描述】:
从下一个测试代码开始
async def hello():
uri = "ws://localhost:8765"
while True:
async with websockets.connect(uri) as ws:
await ws.send("Test \n")
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(hello())
此代码执行每秒发送一条消息的期望行为, 但似乎通过进行如下所示的更改可能会更有效:
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as ws:
while True:
await ws.send("Test \n")
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(hello())
但是,在第二种方法中,上下文管理器退出并输出下一个异常:
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
如果正文在上下文管理器中正确缩进,为什么上下文管理器会关闭连接?
【问题讨论】:
-
请提供带有导入和正确缩进的完整工作代码,以便我们可以重现错误
-
请同时提供完整的错误跟踪,以便清楚哪些行导致错误
标签: python websocket python-asyncio