node.js - How do I get other users socket.id? -


how other user's socket.id?

since socket.id keep changing, whenever browser refresh or disconnect connect again.

for example line of code solve problem

socket.broadcast.to(id).emit('my message', msg);

but question how id?

let jack wants send message jonah

jack use above code send message, how jonah's socket id?

just record, implemented socket.io , passport library use session in socket.io , library call passport-socket.io. user id in socket.io

socket.request.user._id 

what did maintain database model(i using mongoose) containing userid , socketid of connected users. global array. client side on socket connect, emit event along userid

socket.on('connect', function() {     socket.emit('connected', username); //username unique }) 

on server side,

var connect = require('mongoose').model('connect');; /* connect mongoose model used store connected users info*/ socket.on('connected', function(user) { // add user data on connection     var c=new connect({         socketid : socket.id,         client : user     })     c.save(function (err, data) {         if (err) console.log(err);     }); }) socket.on('disconnect', function() { //remove user data model when socket disconnects     connect.findone({socketid : socket.id}).remove().exec();  }) 

this way have connected user info(currently used socketid) stored. whenever need users current socketid fetch as

connect.findone({client : usernameofusertofind}).exec(function(err,res) {     if(res!=null)         io.to(res.socketid).emit('my message', msg); }) 

i used mongoose here instead use array here , use filters fetch socketid of user array.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -