:最近发布的
要 一个房间一样简单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');