How do I get other users socket.id?

2019-07-11 03:38发布

How do I get other user's socket.id?

Since socket.id is keep changing, whenever the browser refresh or disconnect then connect again.

For example this line of code will solve my problem

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

But the question is How do i get that id?

Let say Jack wants to send a message to Jonah

Jack would use the above code to send the message, but how to get Jonah's socket id?

Just for the record, I already implemented socket.io and passport library so that I could use session in socket.io , the library is call passport-socket.io. So to get the user id in socket.io would be

socket.request.user._id

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-11 04:13

What i did for this was to maintain a database model(i was using mongoose) containing userId and socketId of connected users. You could even do this with a global array. From client side on socket connect, emit an event along with userId

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

On server side,

var Connect = require('mongoose').model('connect');; /* connect is mongoose model i used to store currently 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 from model when a socket disconnects
    Connect.findOne({socketId : socket.id}).remove().exec(); 
})

This way always have connected user info(currently used socketId) stored. Whenever you need to get a users current socketId fetch it as

Connect.findOne({client : userNameOfUserToFind}).exec(function(err,res) {
    if(res!=null)
        io.to(res.socketId).emit('my message', msg);
})

I used mongoose here but you could instead even use an array here and use filters to fetch socketId of a user from the array.

查看更多
等我变得足够好
3楼-- · 2019-07-11 04:29

The documentation suggests that `socket.on(SOME_MESSAGE's callback is provided an id as the fist param.

http://socket.io/docs/rooms-and-namespaces/#default-room

javascript io.on('connection', function(socket){ socket.on('say to someone', function(id, msg){ socket.broadcast.to(id).emit('my message', msg); }); });

查看更多
登录 后发表回答