您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Socket.io:如何正确加入和离开房间

Socket.io:如何正确加入和离开房间

:最近发布的

一个房间一样简单socket.join('roomName'

//:JOIN:Client Supplied Room
socket.on('subscribe',function(room){  
  try{
    console.log('[socket]','join room :',room)
    socket.join(room);
    socket.to(room).emit('user joined', socket.id);
  }catch(e){
    console.log('[error]','join room :',e);
    socket.emit('error','Couldnt perform requested action');
  }
})

并 房间,就这么简单socket.leave('roomName');

//:LEAVE:Client Supplied Room
socket.on('unsubscribe',function(room){  
  try{
    console.log('[socket]','leave room :', room);
    socket.leave(room);
    socket.to(room).emit('user left', socket.id);
  }catch(e){
    console.log('[error]','leave room :', e);
    socket.emit('error','Couldnt perform requested action');
  }
})

断开连接事件时无法获取客户端当前所在的房间列表

已修复(添加“断开连接”事件以在断开连接时访问socket.rooms)

 socket.on('disconnect', function(){(
    /*
      socket.rooms is empty here 
      leaveAll() has already been called
    */
 });
 socket.on('disconnecting', function(){
   // socket.rooms should isn't empty here 
   var rooms = socket.rooms.slice();
   /*
     here you can iterate over the rooms and emit to each
     of those rooms where the disconnecting user was. 
   */
 });

现在发送到特定房间:

// sending to all clients in 'roomName' room except sender
  socket.to('roomName').emit('event', 'content');
其他 2022/1/1 18:20:05 有526人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶