套接字断开时如何更改特定用户的状态?

时间:2016-06-02 12:12:20

标签: node.js websocket socket.io

我在这里解决我在套接字连接和断开连接中的问题。我想要这样的东西

 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.
抱歉想要逻辑,但我真的需要它。   提前致谢。 :)

1 个答案:

答案 0 :(得分:0)

在断开连接时,如您所述,您可以根据 this.id socket.id 跟踪ID。

socket.on('disconnect', function() {
    console.log(this.id);
    console.log(socket.id);
});

或者,您可以使用全局数组来处理套接字,如this answer中所述。

如果有适合的那些,你可以对套接字对象进行一些依赖注入

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);
    });
});