According to socket.io examples:
To broadcast, simply add a
broadcastflag toemitandsendmethod calls. Broad
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.
Maybe this will help someone
socket.broadcast.to('room1').emit('updatechat', 'SERVER', username + ' has connected to this room');
see
Nodejs and Socketio Multiroom Chat Tutorial
var customNS = ioserver.of('/chat');
customNS.on('connection', function (socket) {
socket.on('message', function (msg) {
// Send message to sender
socket.emit(msg);
// Send message to everyone on customNS INCLUDING sender
customNS.emit(msg);
// Send message to everyone on customNS BUT sender
socket.broadcast.emit(msg);
// Send message to everyone on ROOM chanel of customNS INCLUDING sender
customNS.in('ROOM').emit(msg);
// Send message to everyone on ROOM chanel of customNS BUT sender
socket.broadcast.in('ROOM').emit(msg);
});
});
also check this answer Send response to all clients except sender (Socket.io)
You solution works if you are working in an evented environment where messages from the client trigger a response to all others, but not if you want the server to sent messages to all clients.
You can do this using io.sockets.emit:
var io = require('socket.io').listen(80);
io.sockets.emit('message', { message: "Hello everyone!" });
However the documentation isn't clear for how to do this to a specific namespace. io.sockets is just a shortcut to io.of(''), as such you can broadcast to everyone on a namespace by calling io.of('/namespace').emit:
var io = require('socket.io').listen(80);
io.of('/admins').emit('message', { message: "Hello admins!" });