套接字断开连接时如何更改特定用户的状态? [英] How to change status of perticular user when socket is disconnect?
本文介绍了套接字断开连接时如何更改特定用户的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里解决我在套接字连接和断开连接方面的问题.我想要这样的东西
II am here to resolve my problem in socket connection and disconnection. I want something like this
1. connection done. (ok) // working
2. on perticular event I am doing to update location of user in database { Here user is online }.
3. But somehow network disconnection the socket will be disconnect and user must be offline. this can be using disconnect event. but I am not aware how to recognise that perticular user has to be updated offline because I don't have user_id in `socket.on('disconnect')` event. please help me out. I googled it everywhere but not helped me out.
抱歉想要逻辑,但我真的需要它.提前致谢.:)
sorry for wanting logic but it is really needed to me. Thanks in advance. :)
推荐答案
在断开连接时,就像您提到的,您可以根据 this.id 或 socket.id跟踪 ID强>.
On disconnect, like you mentioned, you can track the id based on this.id or socket.id.
socket.on('disconnect', function() {
console.log(this.id);
console.log(socket.id);
});
或者,您可以使用全局数组处理套接字,如此答案中所建议一>.
Alternatively, you can handle sockets by using a global array, as suggested in this answer.
如果两者都合适,您可以对套接字对象进行一些依赖注入
If netiher of those are suitable, you can do some dependency injection on the socket object
io.on('connection', function(socket) {
//Obtain the user_id somehow and add it into the socket object
socket.user_id = "hello_world";
socket.on('disconnect', function() {
console.log(socket.user_id);
});
});
这篇关于套接字断开连接时如何更改特定用户的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文