【问题标题】:How to disconnect on a custom event python-socketio如何断开自定义事件 python-socketio
【发布时间】:2021-07-26 09:33:58
【问题描述】:

我有 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.disconnect() 协程是否真的调用了偶数处理程序disconnect
  • 我应该以这种方式发出事件disconnect
@sio.event
async def leaveWorkbench(sid):
    await sio.emit('disconnect')

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

  • 或者我应该简单地将事件处理程序作为一种方法?使用sio.discconect
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)
  • 最后,还有其他“更清洁”的选择吗? 重要提示:我在断开连接时使用session 对象

【问题讨论】:

    标签: python socket.io python-socketio


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2014-01-02
      • 1970-01-01
      • 2016-12-25
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多