Socket.io:使用特定ID将消息发送到特定名称空间

时间:2017-06-29 11:34:07

标签: node.js websocket socket.io

是否可以使用自定义的socket.id ??向具有不同命名空间的套接字发送消息。我正在使用socket.io来创建聊天并发送私人消息。

我成功地设法创建了一个房间并使用

私下发送消息
io.to(room).emit('chatMessage', from, message);

但我还想使用他们的ID向不同名称空间的套接字发送消息,如:

io.of('nameSpace').to(socket.id).emit('chatMessage', from, message); 

我尝试了不同的组合,例如,

io.of('nameSpace').to(socket.id).emit('chatMessage', from, message);

io.of('nameSpace).sockets.socket(socket.id).emit('chatMessage', from, message);

io.to(users[socketid]).emit('chatMessage', from, message);

io.sockets.socket(socketid).emit('chatMessage', from, message);

但它不起作用。是否有其他方法将消息发送到具有不同命名空间的特定客户端?我正在使用房间和命名空间的组合。

注意:我使用的字符串查询等于用户名称作为我的房间名称。

1 个答案:

答案 0 :(得分:1)

此解决方案适用于多个名称空间 假设我们有两个名称空间:

  1. / V1
  2. / v2,套接字ID:LOchCx6DZ8YwPVF8AAAv
  3. 从namespace-1向namespace-2发送消息的语法是

    io.of('/v2').to('/v2#LOchCx6DZ8YwPVF8AAAv').emit('message', 'Hello');
    
相关问题