Socket.io:如何正确加入和离开房间
问题描述:
我试图通过建立一组动态创建的聊天室,在用户进入和离开时发出“已连接”和“已断开”消息来学习Socket.io。看了一下coupleofquestions我已经整合了一些功能,但大部分的响应都来自承认他们已经入侵答案的人,而且我注意到有一种更一般的和最近的讨论关于正确的方式在Socket.io上做这个回购(特别是here和here)Socket.io:如何正确加入和离开房间
因为我是这样的新手,我不知道下面的工作是一种可以接受的方式来做事情,或者它只是偶然的功能,但会导致性能问题或导致听众太多。如果有一种理想的和正式的方式来加入和离开房间,感觉不那么笨重,我很乐意了解它。
客户
var roomId = ChatRoomData._id // comes from a factory
function init() {
// Make sure the Socket is connected
if (!Socket.socket) {
Socket.connect();
}
// Sends roomId to server
Socket.on('connect', function() {
Socket.emit('room', roomId);
});
// Remove the event listener when the controller instance is destroyed
$scope.$on('$destroy', function() {
Socket.removeListener('connect');
});
}
init();
服务器
io.sockets.once('connection', function(socket){
socket.on('room', function(room){ // take room variable from client side
socket.join(room) // and join it
io.sockets.in(room).emit('message', { // Emits a status message to the connect room when a socket client is connected
type: 'status',
text: 'Is now connected',
created: Date.now(),
username: socket.request.user.username
});
socket.on('disconnect', function() { // Emits a status message to the connected room when a socket client is disconnected
io.sockets.in(room).emit({
type: 'status',
text: 'disconnected',
created: Date.now(),
username: socket.request.user.username
});
})
});
答
Socket.IO:最近发布的v2.0.3
雷加丁加入/离开房间[read the docs.]
要加入的房间很简单,只要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');
}
})
告知问题房间用户断开的房间
Not able to get the list of rooms the client is currently in on disconnect event
Has been fixed (Add a 'disconnecting' event to access to socket.rooms upon disconnection)
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');
是我的任何使用的答案吗? – EMX
第一次看到它现在和很久以前一起黑了一些东西,但这似乎是我所寻找的:) – brokyo