socket.io – how to broadcast messages on a namespace?

Seems I was able to solve this for myself after opening a bounty. Sorry about that.

Anyway, see if this helps:

chat.on('connection', function (socket) {
  socket.on('message', function (msg) {
    socket.emit(msg); // Send message to sender
    socket.broadcast.emit(msg); // Send message to everyone BUT sender
  });
});

However, you could save some bandwidth and create a more snappy experience for users if you don’t resend it to the sender. Just add their messages directly to the chat log, and optionally use use only self-emit to confirm it was received without issue.

Leave a Comment