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

前端 未结 4 985
一生所求
一生所求 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 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!" });
    

提交回复
热议问题