1 回答
TA贡献1804条经验 获得超2个赞
recv() 和 send() 都会在关闭的连接上引发 websockets.exceptions.ConnectionClosed 。在那里进行清理工作。
以下是对文档中的 websocket Web 示例的轻微修改:
import asyncio
import datetime
import random
import websockets
async def time(websocket, path):
while True:
now = datetime.datetime.utcnow().isoformat() + "Z"
try:
await websocket.send(now)
except websockets.exceptions.ConnectionClosed:
print("Client disconnected. Do cleanup")
break
await asyncio.sleep(random.random() * 3)
start_server = websockets.serve(time, "127.0.0.1", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
客户端示例:
import asyncio
import websockets
async def hello():
uri = "ws://localhost:5678"
count = 5
async with websockets.connect(uri) as websocket:
while count > 0:
greeting = await websocket.recv()
print(f"< {greeting}")
count = count - 1
asyncio.get_event_loop().run_until_complete(hello())
添加回答
举报