简体   繁体   English

如何断开自定义事件 python-socketio

[英]How to disconnect on a custom event python-socketio

I have the 2 handlers:我有两个处理程序:

@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)

I want to trigger the disconnect event handler (as I want to perform some specific operations on disconnection), but on a custom event named leaveWorkbench .我想触发disconnect事件处理程序(因为我想在断开连接时执行一些特定的操作),但是在一个名为leaveWorkbench的自定义事件上。

  • does sio.disconnect() coroutine actually calls the even handler disconnect ? sio.disconnect()协程实际上调用了偶数处理程序disconnect吗?
  • should I emit an event disconnect this way:我应该以这种方式发出事件disconnect吗:
@sio.event
async def leaveWorkbench(sid):
    await sio.emit('disconnect')

(seems from the docs not a good idea as "reserved"(?) + it would be caught by the client so probably not a working solution) (从文档看来这不是一个好主意,因为“保留”(?)+ 它会被客户端捕获,所以可能不是一个有效的解决方案)

  • or should I simply turn the event handler as a method ?或者我应该简单地将事件处理程序作为一种方法? with use of sio.discconect使用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)
  • At last, other "cleaner" alternatives?最后,其他“更清洁”的替代品? Important note: I make use the session object at disconnection重要说明:我在断开连接时使用session对象

The correct way to do this is to call sio.disconnect(sid) .正确的方法是调用sio.disconnect(sid)

But note that the disconnect() method just initiates a disconnection that then happens in the background.但请注意, disconnect()方法只是启动一个断开连接,然后在后台发生。 The disconnect handler for the affected client will eventually be called, but it may not be immediate (ie may take a second or two).最终会调用受影响客户端的断开连接处理程序,但它可能不会立即调用(即可能需要一两秒钟)。 The client will also be notified that it is being disconnected.客户端也会被通知它正在断开连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM