Flask-socketio断开客户端连接 [英] Flask-socketio disconnect a client
问题描述
我正在使用flask-socketio创建一个聊天应用程序,现在我想在客户端断开连接时(即,当客户端关闭浏览器/选项卡时)使用客户端的用户名向服务器发送消息,以便我可以将该消息从服务器发送到所有现有的客户端客户更改他们的在线朋友列表.我已经在Google上搜索了两个多小时,而我接近的任何东西都是 this 和
I am making a chat application using flask-socketio and now I want to emit a message to server with client's username when a client gets disconnected i.e. when client closes browser/tab so that I can emit that message from server to all existing clients for them to change their online friends list. I have googled for more than two hours and anything I have come close to is this and this but it doesn't work for me. I got a way in flask-socketio docs by the following way in server side but I don't know which client got disconnected so I could not change the online friends list.
@socketio.on('disconnect')
def test_disconnect():
print('Client disconnected')
emit('client disconnected','a client disconnected but I dont know who',broadcast = True) # i have imported emit
# but since i don't know which client disconnected i couldn't emit client name above.
所以,我认为最好像下面这样从客户端发送消息,但是在该客户端关闭浏览器后,服务器不会收到该消息:
So, I think it would be better to send message from client side like following but after that client closes browser,server does not get that message:
// handle disconnect
socket.on('disconnect',()=>{
socket.emit('client disconnected',{'username':localStorage.getItem('username')})
})
我是flask-socketio的新手,任何帮助将不胜感激.
I am new to flask-socketio and any help would be highly appreciated.
推荐答案
您可以使用 onbeforeunload
事件.当浏览器选项卡或窗口关闭时,尝试离开页面导航或重新加载页面,将触发此事件.
You can make use of onbeforeunload
event. This event gets fired, when a browser tab or a window is closing, trying navigate away from the page or reloading the page.
客户端:
<script>
window.onbeforeunload = function () {
socket.emit('client_disconnecting', {'username':localStorage.getItem('username')});
}
</script>
服务器端:
@socket.on('client_disconnecting')
def disconnect_details(data):
print(f'{data['username']} user disconnected.')
这篇关于Flask-socketio断开客户端连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!