我正在尝试通过构建一组动态创建的聊天室来学习 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
});
})
});
原文由 isdn 发布,翻译遵循 CC BY-SA 4.0 许可协议
Socket.IO :最近发布 的 v2.0.3
关于加入/离开房间 [阅读文档]
加入 房间就像
socket.join('roomName'
一样简单)并 离开 一个房间,简单如
socket.leave('roomName');
:通知房间用户正在断开连接
在断开连接事件中无法获取客户端当前所在的房间列表
已修复(添加“断开连接”事件以在断开连接时访问 socket.rooms)
现在发送到特定房间:
Socket.IO 发射备忘单