How do I emit to all members of a room from a socket instance?
I know I can do io.in('room').emit('event', data);
if I have access to the IO instance, but in my case I only have access to the socket of the sender, I store the socket of the user in a user object, and pass it around my code so that I can emit from anywhere, but as a result I have no access to the IO instance.
How can I emit to all members of a room including the sender from the sender’s socket instance?
Advertisement
Answer
Well, it is best to give yourself access to the io
instance in some way so you can do io.in(room).emit(...)
. You can either export it from where you create it and then import it where you are or you can make it available some other way.
Here are four other ways to do it:
Attach .io
property to each socket
In the file, where you create the io
instance, you can attach it as a property to every socket.
// put io on each socket io.on('connection', socket => { socket.io = io; });
Then, on any socket, you can get io
with socket.io
.
Put io
instance in your app
object
If app
is available, then some folks put the io
instance on the app
object with app.set("io", io);
so code elsewhere can get it with io.get("io");
.
Send to both room and self
As a work-around, you could also just send to both:
socket.broadcast(room).emit(...); socket.emit(...);
Use undocumented socket.server
There is also an undocumented property on the socket
which gives you access to the server object. Use at your own risk:
socket.server.in("room").emit(...);
which essentially gives you the io
instance.