【问题标题】:Unsubscribing from subscriptions in socket.io在 socket.io 中取消订阅
【发布时间】:2016-04-27 13:22:16
【问题描述】:

假设我有一个带有 10 行表格的角度页面,每行都有一个 id,并将我重定向到具有唯一 id 的页面。

我想在socket.io中订阅这个id,当我离开这个页面/换到另一个页面时,我想把之前的订阅替换成新的。

我该怎么做?我是否必须将所有当前订阅保存在数据库中?

(我在节点上使用sails.js 框架,在客户端使用angular)。

【问题讨论】:

    标签: javascript angularjs websocket socket.io sails.js


    【解决方案1】:

    当您断开一个套接字(即更改页面到另一个)时,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...

    就是这样!

    【讨论】:

    • 但是我使用的是角度的,所以页面变化并没有真正的断开。
    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2018-07-29
    • 1970-01-01
    • 2022-01-19
    • 2017-12-18
    • 2016-07-27
    相关资源
    最近更新 更多