socket.join(room[, callback])

优质
小牛编辑
118浏览
2023-12-01
  • room (字符串)
  • callback (Function)
  • Return Socket for chaining

添加客户端到room房间内,并且执行可选择的回调函数。

io.on('connection', (socket) => {
  socket.join('room 237', () => {
    let rooms = Objects.keys(socket.rooms);
    console.log(rooms); // [ <socket.id>, 'room 237' ]
    io.to('room 237', 'a new user has joined the room'); // broadcast to everyone in the room
  });
});

加入房间的过程被Adapter适配器处理。

为了更方便开发者,每一个socket自动的通过他自己的id标志创建了一个只属于他自己的房间,这样做,使得当前socket和其他socket之间的广播变得更容易。

io.on('connection', (socket) => {
  socket.on('say to someone', (id, msg) => {
    // send a private message to the socket with the given id
    socket.to(id).emit('my message', msg);
  });
});