首页 > 解决方案 > 如何断开自定义事件 python-socketio

问题描述

我有 2 个处理程序:

@sio.event
async def connect(sid, environ):
    print('connect', sid)

@sio.event
async def disconnect(sid, environ):
    # perform some user management stuff
    # perform some cleaning as well
    print('disconnect', sid)

我想触发disconnect事件处理程序(因为我想在断开连接时执行一些特定操作),但是在一个名为leaveWorkbench.

@sio.event
async def leaveWorkbench(sid):
    await sio.emit('disconnect')

(从文档看来,“保留”(?)不是一个好主意+它会被客户抓住,所以可能不是一个可行的解决方案)

async def disconnect_handler(sid):
    # operations to be performed on disconnection
    await sio.disconnect(sid)??

@sio.event
async def leaveWorkbench(sid):
    await disconnect_handler(sid)

@sio.event
async def disconnect(sid):
    await disconnect_handler(sid)

标签: pythonsocket.iopython-socketio

解决方案


正确的方法是调用sio.disconnect(sid).

但请注意,该disconnect()方法只是启动断开连接,然后在后台发生。最终将调用受影响客户端的断开连接处理程序,但它可能不会立即调用(即可能需要一两秒钟)。客户端也将被通知它正在断开连接。


推荐阅读