Socket.io:如何正确加入和离开房间 [英] Socket.io: How to correctly join and leave rooms
问题描述
我正在尝试通过构建一组动态创建的聊天室来学习 Socket.io,这些聊天室在用户进入和离开时发出已连接"和已断开连接"消息.在看了一个情侣之后of 问题 我已经整理了一些功能性的东西,但大多数链接的回复来自那些承认他们已经把答案拼凑在一起的人,我注意到有一个更普遍的——最近的——关于正确的讨论在 Socket.io 存储库(特别是 此处 和 这里)
I'm trying to learn Socket.io by building a set of dynamically created chatrooms that emit 'connected' and 'disconnected' messages when users enter and leave. After looking at a couple of questions I've put together something functional but most of the response linked are from people who admit they've hacked together answers and I've noticed there's a more general - and recent - discussion about the right way to do this on the Socket.io repo (notably here and here)
由于我是新手,我不知道下面的工作是否是可以接受的做事方式,或者它只是偶然运行但会导致性能问题或导致太多听众.如果有一种理想且正式的加入和离开房间的方式,让我感觉不那么笨拙,我很想了解它.
As I'm such a novice I don't know if the work below is an acceptable way to do things or it just happens to incidentally function but will cause performance issues or result in too many listeners. If there's an ideal - and official - way to join and leave rooms that feels less clunky than this I'd love to learn about it.
客户
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
Socket.IO : recently released v2.0.3
加入一个房间就像socket.join('roomName'
)一样简单
To join a room is as simple as 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');
:
and to leave a room, simple as 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');
这篇关于Socket.io:如何正确加入和离开房间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!