如何获得其他用户的socket.id? [英] How do I get other users socket.id?

查看:34
本文介绍了如何获得其他用户的socket.id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取其他用户的socket.id?

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

由于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);

但是问题是我如何获取该ID?

But the question is How do i get that id?

假设杰克想向乔纳发送消息

Let say Jack wants to send a message to Jonah

Jack将使用上面的代码发送消息,但是如何获取Jonah的套接字ID?

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

仅作记录,我已经实现了 socket.io passport 库,以便可以在 socket.io 中使用会话库称为 passport-socket.io .因此,要在socket.io中获取用户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

推荐答案

我为此所做的是维护一个数据库模型(我使用的是Mongoose),其中包含已连接用户的userId和socketId.您甚至可以使用全局数组来执行此操作.从客户端通过套接字连接,与userId一起发出事件

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
})

在服务器端,

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(); 
})

通过这种方式始终存储已连接的用户信息(当前使用的socketId).每当您需要获取用户当前的socketId时,都将其提取为

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);
})

我在这里使用了猫鼬,但您甚至可以在此处使用一个数组,并使用过滤器从该数组中获取用户的socketId.

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.

这篇关于如何获得其他用户的socket.id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆