简体   繁体   English

如何存储套接字 ID 并发送给该用户

[英]How to store socket id and emit to that user

Hey guys i am working on a webrtc app using socket.io and node, and i have this issue where i made a database in mongodb to store every admin who created a room then fetch the admin id when a user joins the room, but my problem is how do i store the id and emit to that specific user.嘿伙计们,我正在使用 socket.io 和 node 开发 webrtc 应用程序,我遇到了这个问题,我在 mongodb 中创建了一个数据库来存储创建房间的每个管理员,然后在用户加入房间时获取管理员 ID,但是我的问题是我如何存储 id 并发送给该特定用户。 i tried using io.to(socketID).emit(event,message) but it doesn't emit to the user please help my code我尝试使用 io.to(socketID).emit(event,message) 但它没有发送给用户请帮助我的代码

const users = {} 
const admins = {}


io.on('connection',socket =>{

socket.on('join-class',async(classId,palsid)=>{
  
      socket.join(classId)

      const gEtLectID = await LiveClass.findOne({"address":classId})
      if(gEtLectID){
        socketId = gEtLectID.startedBy 
      }
      console.log(socketId,'is admin')
      io.to(socketId).emit('user-connected', "let's play a game");
      
      // socket.to(admins[socket.id]).emit('user-connected',userID)
      

      //on disconnection
      socket.on('disconnect',()=>{
          socket.to(classId).broadcast.emit('user-disconnect',palsid)
      })

   
  })
  

You need to handle the id in the client.您需要在客户端处理 id。 when you send an event to the server, include the toId and fromId.当您向服务器发送事件时,包括 toId 和 fromId。 So, in the client var socket = io("http://127.0.0.1:3000/", { query: "id=4ny1d" });所以,在客户端var socket = io("http://127.0.0.1:3000/", { query: "id=4ny1d" }); . .

And in the server并且在服务器中

io.on('connection', socket => {

    var id = socket.handshake.query['id'];

    socket.leave(socket.id);//leaving default room
    socket.join(id);//joining to custom room(this is admin room)

    //maybe you'll want a roomId, but the steps are the same

    socket.on('join-class', data => {

        socket.join(data.classId);//Here you join to the class
        socket.emit('class-ready', data);//message with class info to the suscriber

        //here you can store classId in a var or in an array to use socket.to().emit()

    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM