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

我正在尝试通过构建一组动态创建的聊天室来学习Socket.io,这些聊天室在用户进入和离开时会发出“已连接”和“已断开”消息。看着问题,我已经把一些功能,但大多数链接的响应是从谁承认自己已成功侵入一起答案的人,我已经注意到有一个更普遍的-和最近-

有关的权利的方式来讨论在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.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');

Socket.IO发射备忘单

以上是 Socket.io:如何正确加入和离开房间 的全部内容, 来源链接: utcz.com/qa/431730.html

回到顶部