简体   繁体   English

如何在Socket.IO中向特定名称空间的客户端广播消息?

[英]How to broadcast message to clients of the certain namespace in Socket.IO?

Here is a sample from socket.io website: 这是来自socket.io网站的示例:

var io = require('socket.io').listen(80);

var chat = io
  .of('/chat')
  .on('connection', function (socket) {
    socket.emit('a message', {
        that: 'only'
      , '/chat': 'will get'
    });
    chat.emit('a message', {
        everyone: 'in'
      , '/chat': 'will get'
    });
  });

var news = io
  .of('/news')
  .on('connection', function (socket) {
    socket.emit('item', { news: 'item' });
  });

normally I use io.sockets.emit(...) to broadcast data to the clients. 通常我使用io.sockets.emit(...)将数据广播到客户端。 But how to broadcast messages to clients connected with namespace? 但是如何向与名称空间连接的客户端广播消息? In other words how to send message to all clients subscribed to news, and not to those who subscribed to chat? 换句话说,如何向所有订阅新闻的客户而不是向订阅聊天的客户发送消息?

UPDATE: I guess I know the answer: 更新:我想我知道答案:

news.sockets.emit(...);

am I correct? 我对么?

From an official example on github : 来自github上的官方示例

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.join('justin bieber fans');
  socket.broadcast.to('justin bieber fans').emit('new fan');
  io.sockets.in('rammstein fans').emit('new non-fan');
});

So if you want to send a message to all the connected clients in a namespace you can use io.sockets.in('namespace').emit('message') . 因此,如果要将消息发送到命名空间中的所有已连接客户端,则可以使用io.sockets.in('namespace').emit('message')

You can try to use the following: 您可以尝试使用以下方法:

io.of('/news').emit('data', data);

In my case it works(version "socket.io":"^1.0.0-pre2" ). 就我而言,它可以工作(版本"socket.io":"^1.0.0-pre2" )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM