I want to know that if 2 users in a room are online or not. if both are online then I want to tell it to the room that the user is online but I can't find a way to know how to tell they are online.
I have a global array which stores the acc_id of all the socket.id and gets updated everytime the socketid changes, by this I can know the user has not open another tab as a new tab gives a new client.
io.of('/').in(room).clients(function(error, clients) {
console.log(clients.length);
clients.forEach(function(iiid){
ds.some(function(el) {
if (el.socket_id === iiid && el.acc_id !== decrypted && clients.length >= 2) {
io.to(room).emit('isasdjfg__-dfko', {
dfhdf: "Oui", //Yes in French
pfg: room
});
}
});
});
});
This checks if the clients in the room have a acc_id that is not equal to the current user id means if there are 2 people in the room, but this doesn't works.
The below code contains a users
array
in the server
. When a user connects it sends a connect event with an id
. That id
is stored in the users array
. When the user disconnects
the id
is removed from the array. So you can make a condition when the user id is in the array user is online
else offline
.
if(users.includes(id))
console.log('online')
For checking if 2 users with id1 and id2 respectively are online
if(users.includes(id1) && users.includes(id2))
console.log("both are online")
Server
var users = [];
io.on('connection', function(socket){
socket.on('connect', function(data){
users[socket.id] = data.id;
});
socket.on('disconnect', function(){
users.splice(socket.id,1);
});
});
Client
var socket = io();
socket.emit('connect',{id:'id'});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.