当您断开一个套接字(即更改页面到另一个)时,socket.io 会自动取消订阅您的套接字。
要订阅房间,您只需在连接 id 时从 angular 发送消息,然后在您的sails 控制器中为用户订阅 id
编辑
就像this 页面所说,你需要实现你的系统来跟踪套接字。
首先,在 /api/services/ 中创建一个服务并将其放入:
module.exports = {
switchRoom: function (socket, to_id) {
var tmp = _.find(sails.mysubscribers, function (sub) {
return sub.socket === socket;
});
if (tmp) { // If user came from another page unsuscribe him
sails.sockets.leave(socket, 'Unique prefix' + tmp.roomId);
} else {
tmp = {
socket: socket
};
sails.mysubscribers.push(tmp);
}
if (!to_id) { // If the user leave remove him from the array
var index = sails.mysubscribers.indexOf(tmp);
if (index > -1) sails.mysubscribers.splice(index, 1);
} else {
tmp.roomId = to_id;
sails.sockets.join(socket, 'Unique prefix' + to_id);
}
}
};
然后,在 /config/sockets.js 中编辑 afterDisconnect 函数:
module.exports.sockets = {
afterDisconnect: function (session, socket, cb) {
YourService.switchRoom(socket);
return cb();
}
};
现在,当您需要 switchRoom 时,您只需调用 YourService.switchRoom(req.socket, roomId) 其中 roomId 是 angular 发送的 id...
就是这样!