【问题标题】:socket.io create dynamic roomsocket.io 创建动态房间
【发布时间】:2013-10-18 13:13:47
【问题描述】:

我已经在谷歌上搜索了 2 天,以使用 nodeJs 在 socket.io 上动态创建房间。当我为服务器创建一个房间时,我会这样:

socket.on('follow_me', function (user_id) { //I use the user_id of the user to create room

    socket.join(user_id);

    console.log(server.sockets.manager.rooms);
});

如果接下来,我想通过使用向所有连接的人发送消息

socket.join(user_id);

当我使用时:

socket.on('message', function (data) {

    socket.broadcast.to(data.room).emit('recieve',data.message); //emit to 'room' except this socket

});

这个房间的其他用户没有收到消息;但如果我使用:

socket.join(user_id);`,when i use :

    socket.on('message', function (data) {

    socket.broadcast.emit('recieve',data.message);

});

所有用户都会收到消息。为什么房间不适合我?我认为代码很好!

坦克的

【问题讨论】:

标签: node.js socket.io


【解决方案1】:
socket.on('message', function (data) {
        /*considering data.room is the correct room name you want to send message to */
        io.sockets.in(data.room).emit('recieve', data.message) //will send event to everybody in the room while 
        socket.broadcast.to(data.room).emit('recieve', data.message) //will broadcast to all sockets in the given room, except to the socket which called it
        /* Also socket.broadcast.emit will send to every connected socket except to socket which called it */
    });

我猜你需要的是io.sockets.in

【讨论】:

  • 坦克的这个答案。我的问题是我的错误。io.sockets.in(data.room).emit('recieve', data.message) 帮助发现我的代码中的错误,现在我继续使用 socket.broadcast.to(data.room).emit('recieve', data.message) 没有任何问题。socket.io 的代码很好。坦克对所有人
猜你喜欢
  • 1970-01-01
  • 2018-12-11
  • 2020-01-10
  • 2013-10-10
  • 2013-10-09
  • 2017-05-10
  • 2019-06-13
  • 2016-05-08
  • 2011-10-14
相关资源
最近更新 更多