【问题标题】:How to change status of perticular user when socket is disconnect?套接字断开连接时如何更改特定用户的状态?
【发布时间】:2016-10-02 04:07:47
【问题描述】:

我来这里是为了解决我的套接字连接和断开问题。我想要这样的东西

 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.

很抱歉需要逻辑,但我确实需要它。 提前致谢。 :)

【问题讨论】:

  • 在套接字连接上,在套接字对象上创建一个新属性,如 socket_object.user_id = 'XXXXX' 以及何时执行断开连接事件。你的socket_object上有那个user_id,你可以随意使用它。或者您可以使用 Redis 以套接字 id 作为密钥保存套接字相关数据,当套接字断开连接时,您可以从 redis 获取所有数据并执行您想要的工作并在此之后删除 redis 密钥

标签: node.js websocket socket.io


【解决方案1】:

在断开连接时,就像您提到的那样,您可以根据 this.idsocket.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);
    });
});

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 2015-10-31
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多