socket.to(room)

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

设置修改器,使得随后的事件导向这样的一种情况:即仅向当前房间的客户端广播消息(主动广播消息的一方除外)。

为了能对多个房间触发同一个广播,你需要给多个房间链式的执行几次to方法。

io.on('connection', (socket) => {
  // to one room
  socket.to('others').emit('an event', { some: 'data' });
  // to multiple rooms
  socket.to('room1').to('room2').emit('hello');
  // a private message to another socket
  socket.to(/* another socket id */).emit('hey');
});

注意:广播消息下执行emit方法,是无法传入确认消息是否接收的回调函数的,原因你懂的。