在socket.io中断开连接时更新node.js中的数组
我正在尝试创建一个新的socket.io实时分析连接。我有两种类型的用户。普通用户及其驱动程序 这是授权代码在socket.io中断开连接时更新node.js中的数组,node.js,sockets,socket.io,Node.js,Sockets,Socket.io,我正在尝试创建一个新的socket.io实时分析连接。我有两种类型的用户。普通用户及其驱动程序 这是授权代码 io.configure(function() { io.set('authorization', function(handshake, callback) { var userId = handshakeData.query.userId; var type = handshakeData.query.type;
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()
{
});
我想删除我在断开连接时添加的用户名。我该怎么做呢。我可以向套接字添加任何内容吗?或者我应该做什么?如果您只是试图从
用户和驱动程序数组中删除用户ID
,您可以执行以下操作:
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);
});
此代码假定您将其放在存在userId
变量的同一个闭包中。如果您没有这样做,那么您可能需要将userId
作为socket对象的属性,以便在需要时可以访问它。您不会显示代码的组织方式或事件处理程序的位置等更大的上下文,因此我们无法在没有看到这些的情况下提出更具体的建议