skip to Main Content

Hey guys please i need help emiting data to a specific user in a specific room using socket.io, am using redis to store the id’s of the admin who created the group, but how do i get the userid from redis and emit to them in their room

my code

const users = {} 
const admins = {}


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

socket.on('create-class',(address,userID)=>{
  client.hmset(`${userID}`, `id`, `${userID}`); 
})


socket.on('join-class',(classId,palsid)=>{
  
      socket.join(classId)
      client.hgetall(`${palsid}`, function(err, object) {
        if(err)throw err
          
          if(object !==null){
            admins[socket.id] = object.id 
          }
         
           socket.to(classId).broadcast.emit('user-connected',palsid)
       
    });                    
     
      

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

   
  })

2

Answers


  1. Chosen as BEST ANSWER

    first of all i didn't know if you refresh a page the socket id changes so i made a button at the frontend that sends a signal to the server, identifying the user as admin the server takes the socket id saves to redis, when any user joins that particular room the server jus fetch that admin id and send to the user connecting, allowing them to share their stream. then using io.to(socketID).emit('user-connected', palsid); to emit back to just the admin socket. so any user who gets connected to that room the stream is sent to just the admin and not everyone else in the room making it a one to many video conference

    my front end code

    //for button
    <Button onClick={this.setAdmin}>send stream</Button>
    
    the function
    setAdmin=()=>{
            console.log(socket.id)
                socket.emit('create-class',this.props.match.id,socket.id)
            }
    

    my backend code

    io.on('connection',socket =>{
    
    socket.on('create-class',(address,socketID)=>{
      //save to redis so all client can connect to this socket
      client.set("adminsocket",socketID,(err)=>{
        if(err)throw err;
      })
      
    })
    socket.on('join-class',async(classId,palsid)=>{
          socket.join(classId)
    //Fetch the socket.id from redis
    client.get("adminsocket",(err,socketID)=>{
      if(err) throw err
        io.to(socketID).emit('user-connected', palsid);
    })
       
          //on disconnection
          socket.on('disconnect',()=>{
              socket.to(classId).broadcast.emit('user-disconnect',palsid)
          })
    
       
      })
    

  2. Based on the information OP offers I can only give a few pointers.

    First you need to get the socket (specific user), ideally by its id.

    const socket = io.sockets.connected[socketid];
    

    Then you just emit to this socket

    socket.emit("message", "hello world");
    

    This should send a message to one specific socket (user), independent from which room it is in. This still leaves the question on where to get the socketid, but to answer that we need more information about your code/setup/app. Usually socket ids are kept in some sort of store/database or memory.

    Keep reference to the socket id

    Now, the socket id is something temporary. Whenever a socket connects, it gets a different socket id. How would one identify one specific user to any socket if the socket id is temporary ?

    A : Store a reference to the socket id using something non-temporary

    When a user is connecting to the websocket server, there is a chance he/she does that along with a unique user id. If you have a database of users, they all have an unique identifier (usually). Keep this identifier together with the socketid when the socket is connecting and you will have reference to the socket at any later point in time using the unique user identifier. There are different ways on how to pass a long something like a user id while the socket is connecting : you can use a query token for example :

    // client side
    const ioClient = require('socket.io-client');
    ioClient(url + '/?token=aaaabbbbccccdddd');
    
    // server side
    io.on('connection', function(socket) {
    
      const userid = socket.handshake.query.token; // aaaabbbbccccdddd
      inMemoryStore.sockets[userid] = socket.id;
        
    });
    

    B : Use non-temporary id as socket id

    There is also the option to set your own custom socketid per socket. Like this you could use the user id or any other non-temporary identifier as socket id directly. Something like this :

    // server side
    io.engine.generateId = (req) => {
      return req.query.token;
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search