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

左心房为你撑大大i 提交于 2019-11-28 15:43:14

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.

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!" });
smbeiragh
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)

Shimon Doodkin

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!