node.js - How to show online and offline properly using socketio -


so far have been doing testing on online , offline features using socketio, stumble upon weird bug. bug

user (browser a) , user b (browser b)

when user open browser, connected via socketio user b.

how make both of them online, 1 of them online , other not online

i got socket.request using passport.socketio module, every logged in user connected via library

here's code serverside

   io.on('connection', function(socket) {       // happen whenever user online.      user.findbyid({ _id: socket.request.user._id}, function(err, founduser) {        if (err) console.log(err);        founduser.socketid = socket.id;       founduser.online = true;       founduser.save(function(err) {         if (err) console.log(err);         socket.broadcast.emit('connection', 'online');       });     });      socket.on('disconnect', function() {       user.findbyid({ _id: socket.request.user._id}, function(err, founduser) {          if (err) console.log(err);          founduser.online = false;         founduser.save(function(err) {           if (err) console.log(err);           socket.broadcast.emit('connection', 'offline');         });       });     });  }); 

clientside socket.js

socket.on('connection', function(data) {   $('#online').html(data); });  socket.on('disconnect', function() {   $('#online').html("offline"); }); 

clientside test.html

<button type="button" id="online" class="btn btn-default"></button> 

how show both of them online or offline @ same time?

whenever user a' refresh --> user b's page showing user online

while

on user a's page, user b not online , vice versa

although both of them connected via socket.

it seems me missing 2 things.

1) initial state/list of online users, sent clients on startup.

2) when there online/offline event, send user went online/offline clients, clienta notices clientb went online.


edit: code requested... @ least pseudocode:

ps: assume "broadcast" sends clients.

function onlineusers() {     var _users;     user.findallby({online:true}, function(err, users){         _users = json.stringify(users);     });     return _users; }  io.on('connection', function(socket) {     // let clients know online on startup.     socket.emit("receiveonlinelist", onlineusers());      // .... stuff too, but...     // notice "founduser" param, know went online.     // same disconnect.     socket.broadcast.emit('connection', 'online', founduser);  }); 

note code not work, don't know io, nor know libs using persistance.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -