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
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
my backend code
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.
Then you just emit to this socket
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 :
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 :