我需要在执行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无法从服务器中删除。
抱歉我的英文
答案 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);
});
};