我正在尝试创建一个新的 socket.io 实时分析连接。我有两种类型的用户。普通用户及其驱动程序。
这是授权代码
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。我该怎么做呢。我可以向套接字添加任何内容吗?或者我应该做什么?
最佳答案
如果您只是尝试从 users
和 drivers
数组中删除 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);
});
此代码假设您将其放入 userId
变量所在的同一个闭包中。如果您不这样做,那么您可能需要将 userId
作为套接字对象的属性,以便在需要时可以访问它。您没有显示代码的组织方式或事件处理程序所在位置的更大上下文,因此我们无法在没有看到这些内容的情况下提出更具体的建议。
关于node.js - 在 socket.io 中断开连接时更新 node.js 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32844892/