admin管理员组文章数量:1289911
In javascript, we have WebSocket.onclose()
for doing some stuff when a websocket connection is closed by the server. Is there a way to do the same in a Python server when the connection is closed by the client device? The server is run using the websockets
module itself using the websockets.serve()
method. Both the .Connected
& .ConnectionClosed
aren't attributes of WebSocketServerProtocol
(or so the error says). Any help would be appreciated.
In javascript, we have WebSocket.onclose()
for doing some stuff when a websocket connection is closed by the server. Is there a way to do the same in a Python server when the connection is closed by the client device? The server is run using the websockets
module itself using the websockets.serve()
method. Both the .Connected
& .ConnectionClosed
aren't attributes of WebSocketServerProtocol
(or so the error says). Any help would be appreciated.
2 Answers
Reset to default 7Both recv() and send() will raise a websockets.exceptions.ConnectionClosed on a closed connection. Handle your cleanup there. See https://websockets.readthedocs.io/en/stable/howto/cheatsheet.html
Here's a slight modification of the websocket web example from the docs:
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_plete(start_server)
asyncio.get_event_loop().run_forever()
Example client:
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_plete(hello())
To monitor closed websocket client connections from the server:
async def browser_server(websocket, path):
closed = asyncio.ensure_future(websocket.wait_closed())
closed.add_done_callback(lambda task: your_on_close_action())
https://github./python-websockets/websockets/issues/243
本文标签: javascriptPython websockets oncloseStack Overflow
版权声明:本文标题:javascript - Python websockets onclose - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741446929a2379256.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论