从下一个测试代码
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
如果正文在上下文管理器中正确缩进,为什么上下文管理器会关闭连接?
您可能正在关注websockets
库示例。
如示例中所写:
在服务器端,websockets 为每个 WebSocket 连接执行一次处理程序协程 hello。它在处理程序协程返回时关闭连接。
以下是示例中的 Websockets 服务器:
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
并将 Websockets 客户端修改为使用while True
循环:
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
name = input("What's your name? ")
while True:
print(websocket.closed)
await websocket.send("Test")
await asyncio.sleep(1)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())
运行服务器,然后客户端提供以下输出:
在服务器中:
< Test
> Hello Test!
在客户端:
What's your name? hi
False
True
...
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
在您介绍的第一种情况下,代码在每次循环迭代时都会创建 websocket 连接。而在第二个中,代码重用了服务器在按照文档说明处理后关闭的连接。您可以websocket
通过检查websocket.closed
字段看到连接已关闭。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句