Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Socket.Io how to emit to all members in a room from a socket instance including the sender

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!