断开后删除套接字

时间:2016-05-02 14:17:09

标签: javascript node.js socket.io

我需要在执行socket.disconnect()

后从服务器中删除套接字
users = {}
ids_disconnect = []

io.of('/example')
    .on('connection', function (socket) {
        var user_id = socket.decoded_token.user;


        if(users[user_id] === undefined){
            users[user_id] = {"socket": socket};
        } else {
            ids_disconnect.push(users[user_id].socket.id);
            users[user_id].socket.disconnect(true);
            users[user_id] = {"socket": socket};
        }

        console.log("User Connect: " + user_id + " SocketID: " + socket.id);



        //disconnect client
        socket.on('disconnect', function () {
            console.log('User Disconnect ' + user_id);
            if(ids_disconnect.indexOf(socket.id) != -1){
                console.log('Disconnect Force: ' + user_id );
                ids_disconnect.splice(ids_disconnect.indexOf(socket.id),1)
            } else {
                delete users[user_id];
            }
        });
    });

};

这是我的代码,但socket无法从服务器中删除。

抱歉我的英文

1 个答案:

答案 0 :(得分:0)

在触发之前,您必须先听取disconnect事件。

users = {}
ids_disconnect = []

io.of('/example')
  .on('connection', function(socket) {
    var user_id = socket.decoded_token.user;
    //disconnect client
    socket.on('disconnect', function() {
      console.log('User Disconnect ' + user_id);
      if (ids_disconnect.indexOf(socket.id) != -1) {
        console.log('Disconnect Force: ' + user_id);
        ids_disconnect.splice(ids_disconnect.indexOf(socket.id), 1)
      } else {
        delete users[user_id];
      }
    });

    if (users[user_id] === undefined) {
      users[user_id] = {
        "socket": socket
      };
    } else {
      ids_disconnect.push(users[user_id].socket.id);
      users[user_id].socket.disconnect(true);
      users[user_id] = {
        "socket": socket
      };
    }

    console.log("User Connect: " + user_id + " SocketID: " + socket.id);
  });
};