javascript Python网络套接字打开关闭

yebdmbv4  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(113)

在javascript中,我们有WebSocket.onclose()来在服务器关闭WebSocket连接时做一些事情。当客户端设备关闭连接时,有没有办法在Python服务器中做同样的事情?服务器是使用websockets.serve()方法通过websockets模块本身运行的。.Connected.ConnectionClosed都不是WebSocketServerProtocol的属性(或者错误是这么说的)。任何帮助都将不胜感激。

vyswwuz2

vyswwuz21#

recv()和send()都将在已关闭的连接上引发一个websockets.exceptions.ConnectionClosed。在那里处理您的清理。请参见https://websockets.readthedocs.io/en/stable/howto/cheatsheet.html
下面是对来自文档的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())

相关问题