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

前端 未结 4 987
一生所求
一生所求 2020-12-12 14:30

According to socket.io examples:

To broadcast, simply add a broadcast flag to emit and send method calls. Broad

相关标签:
4条回答
  • 2020-12-12 14:50

    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.

    0 讨论(0)
  • 2020-12-12 14:52

    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

    0 讨论(0)
  • 2020-12-12 14:57
    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)

    0 讨论(0)
  • 2020-12-12 15:06

    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!" });
    
    0 讨论(0)
提交回复
热议问题