取消订阅socket.io中的订阅
问题描述:
比方说,我有一个带有10行的表格,每行都有一个ID,并将我重定向到具有唯一ID的页面。取消订阅socket.io中的订阅
我想在socket.io中订阅此ID,当我将此页/更改为另一个时,我想将以前的订阅替换为新订阅。
我该怎么做?我是否必须将所有当前订阅保存在数据库中?
(我在节点上使用sails.js框架,在客户端使用角度)。
答
当您断开一个套接字(即将页面更改为另一个套接字)时,socket.io将自动删除您的套接字。
要订阅一个房间,你可以简单地当你的ID连接,然后在你的船帆控制器您订阅用户的ID
编辑
像this发送从角消息页面说,你需要实现你的系统来跟踪套接字。
首先,创建/ API /服务的服务/放认为:
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();
}
};
现在,当您需要切换房间,您只需拨打YourService.switchRoom(req.socket, roomId)
,其中roomId是通过角度发送的身份证...
就是这样!
但我使用角度,所以没有真正的页面更改断开连接。 – user3712353
我用这种方式编辑答案;) –