2

What's the best way to send a message via socket io to a group of users, for example only those in a specific chat room instead of all users?

I am aware of Sending data only to chosen users using Socket.io-node but socketio version .7 was released recently and seems like there might be a more elegant way with the new api using either get/set or namespacing?

Community
  • 1
  • 1
jhchen
  • 14,355
  • 14
  • 63
  • 91

1 Answers1

10

I think you should look up room concept:

Rooms

Sometimes you want to put certain sockets in the same room, so that it's easy to broadcast to all of them together.

Think of this as built-in channels for sockets. Sockets join and leave rooms in each socket.

Server side:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.join('justin bieber fans');
  socket.broadcast.to('justin bieber fans').emit('new fan');
  io.sockets.in('rammstein fans').emit('new non-fan');
});
Community
  • 1
  • 1
Alfred
  • 60,935
  • 33
  • 147
  • 186
  • 1
    In this example, everyone would be a member of the `justin bieber fans` room. Suppose on connection the client sent a group ID they were a member of, could one simple create a room, and emit to a room using a variable, like so ` `group${groupID}` ` ? – John Jan 15 '20 at 00:38