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. i tried using io.to(socketID).emit(event,message) but it doesn't emit to the user please help my code
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. when you send an event to the server, include the toId and fromId. So, in the client 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()
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.