在socket.io中断开连接后更新node.js中的数组

我正在尝试创build一个新的socket.io实时分析连接。 我有两种types的用户。 普通用户及其驱动程序。

这是授权的代码

io.configure(function() { io.set('authorization', function(handshake, callback) { var userId = handshakeData.query.userId; var type = handshakeData.query.type; var accessKey = handshakeData.query.accessKey; var query = ""; if(type = '') query = 'SELECT * FROM users WHERE id = ' + userId + ' AND accessKey = ' + accessKey; else query = 'SELECT * FROM drivers WHERE id = ' + userId + ' AND accessKey = ' + accessKey; db.query(query) .on('result', function(data) { if(data) { if(type == '') { var index = users.indexOf(userId); if (index != -1) { users.push(userId) } } else { var index = drivers.indexOf(userId); if (index != -1) { drivers.push(userId) } } } else { socket.emit('failedAuthentication', "Unable to authenticate"); } }) .on('end', function(){ socket.emit('failedAuthentication', "Unable to authenticate"); }) }); }); 

断线我有这个

  socket.on('disconnect', function() { }); 

我想删除非常userId我断开连接添加。 我将如何做到这一点。 我可以将任何东西添加到套接字或我应该怎么做?

如果你只是想从你的usersdrivers数组中删除userId ,你可以这样做:

 socket.on('disconnect', function() { // remove userId from users and drivers arrays var index; index = users.indexOf(userId); if (index !== -1) { users.splice(index, 1); } index = drivers.indexOf(userId); if (index !== -1) { drivers.splice(index, 1); } }); 

或者,你可以干一点:

 function removeItem(array, item) { var index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); } } socket.on('disconnect', function() { removeItem(users, userId); removeItem(drivers, userId); }); 

这段代码假定你把它放在userIdvariables所在的同一个闭包中。 如果你不这样做,那么你可能需要将userId作为一个属性放在套接字对象上,以便在你需要的时候访问它。 您不会显示更大的代码组织结构或事件处理程序的位置,因此我们无法看到更具体的build议。